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,926,275
69,926,780
clFFT: Calculating overlapped FFTs
I want to create a batch for clFFT to calculate 3 FFTs of 256 length, where the FFT input values overlap (FFT overlap processing) Input: a 1D array of 276 complex numbers Task: Calculate FFTs for [0..255], [10..265], [20..275] Output: 3x 256 FFTs = 768 values. If I where to write a loop, it would look like this: std::complex<float> *input; for (int i=0; i<3; ++i) { calcFFT(input, input+256); input += 10; } IOW: The fft calculates 256 input values then advances 10 values and calculates the next 256 values. How do I set up a clFFT plan, so that this happens in one call? clfftSetPlanIn/OutStride specifies the distance between the individual values, so that is the wrong parameter. It looks as if clfftSetPlanDistance might be what I need. Doc says: CLFFTAPI clfftStatus clfftSetPlanDistance( clfftPlanHandle plHandle, size_t iDist, size_t oDist ); Pitch is the distance between each discrete array object in an FFT array. This is only used * for 'array' dimensions in clfftDim; see clfftSetPlanDimension (units are in terms of clfftPrecision) which I find very confusing.
Yes, clfftSetPlanDistance is the right API to use. In the example I would have to use cllSetPlanDistance(plan, 10, 256); to calculate FFTs with a step of 10. This will generate OpenCL code where the global offset of the first FFT index is calculated like this: // Inside the generated fft_fwd OpenCL function iOffset = (batch/32)*10 + (batch%32)*8; where batch is the batch number of the FFT to calculate.
69,926,393
69,926,562
How to align the console output to decimal point instead of left or right
I am trying to align the console output in C++ to a decimal point. I have tried the setw, precision options and other flags that aligns to right or left. But none of those has worked satisfactorily. The closest option is to use showpos to print (+) sign for positive numbers, but it disturbs the other formatting such as "TE_1_0" to "TE_+1_+0" 1.000000 -0.000000 0.000000 -0.000000 1.000000 0.000000 0.000000 0.000000 1.000000 It will be nice to have it aligned to decimal point to present the output to the people who are interested in. So any help will be much appreciated.
You can do this with a combination of setw, setfill, fixed and setprecesion as follows: #include <iostream> #include <vector> #include <iomanip> int main() { std::vector<std::vector<double>> vec{{10.0233, 122.1, 1203.1},{100.03, 22.15, 3.01},{107.03, 152.1, 0.1},}; for(std::vector<double> tempVec: vec) { for(double elem: tempVec) { std::cout << std::setw(8) << std::setfill(' ') << std::fixed << std::setprecision(3) << elem << " "; } std::cout<< std::endl; } return 0; } The output of the above is: 10.023 122.100 1203.100 100.030 22.150 3.010 107.030 152.100 0.100 If you modify the above example slightly as shown below: std::cout << std::setw(12) << std::setfill(' ') << std::fixed << std::setprecision(6) << elem << " "; Then the output becomes: 10.023300 122.100000 1203.100000 100.030000 22.150000 3.010000 107.030000 152.100000 0.100000 setw is used to set the maximum length of the output, which was 8 and 12 in my given example. setfill is used to fill the padding places with a char.
69,926,782
69,936,938
how do I initialize rapidjson buffer at each while loop?
I'm currently sending rapidjson::Value of array type called databuf to a websocket from boost library. Here is how I load databuf at each loop. rapidjson::Value databuf(kArrayType); databuf.SetArray(); for (size_t j = 0; j < sizeof(pu8resbuf); j++) { if(databuf.IsNull() == true) { printf("databuf is null!\n"); } databuf.PushBack(Value().SetInt(pu8resbuf[j]),allocator); } Then, I pushback the databuf to another rapidjson::value of type array called payload and prepare the string to send it to the websocket as below. payload.SetArray(); payload.PushBack(databuf, allocator); auto raw_key = std::string(std::string("payload-") + std::to_string(m_count_objects/60) + "-" + std::to_string(m_count_objects).c_str()); rapidjson::Value key(raw_key, allocator); rapidjson::StringBuffer bufferJson; jsonDocumentDataSending.AddMember(key, payload, allocator); bufferJson.Clear(); rapidjson::Writer<rapidjson::StringBuffer> writer(bufferJson); jsonDocumentDataSending.Accept(writer); std::string stringForSending = std::string(bufferJson.GetString()); std::shared_ptr<std::string> ss(std::make_shared<std::string>(stringForSending)); messageQ.push_back(ss); if(!messageQ.empty()) { ws_.write(net::buffer(*messageQ.front())); messageQ.pop_back(); databuf.SetArray(); } The following is the result I've got on the frontend regarding the incoming packets from the websocket. As you can see the packets sent are getting longer at each loops as if the sending buffer is not resetting for some reason. Does anyone know what to fix in my code?
I've reset the writer and clear the bufferJson as well like below but didn't work. bufferJson.Clear(); bufferJson.Flush(); rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(bufferJson); writer.Reset(bufferJson); jsonDocumentDataSending.Accept(writer); What worked for me was swapping the document after sending the packet to websocket, and I did it as below. if(!messageQ.empty()) { ws_.write(net::buffer(*messageQ.front())); messageQ.pop_back(); databuf.SetArray(); Value(kObjectType).Swap(jsonDocumentDataSending); }
69,926,911
69,930,187
Which operators implictly define / generate other operators in C++?
I know that defining certain operators in C++ lets the compiler generate other operators for a class. From what I read in this cppreference article it seems like the following holds true: operator== must be explicitly defined (perhaps as default) to be usable. operator!= is generated from operator== if it is not defined explicitly and operator== is defined. operator<=> generates the other four relational operators (if all goes to plan, that is operator<=> returns a result possible to interpret by the other four and is well defined for both the original and reverse parameter orders) operator<=> does NOT generate operator== even if it returns std::strong_ordering which, as I understand, should return an object comparable as equal to 0 if and only if the two compared objects are identical (indistinguishable). I tested this myself with the following code #include <iostream> class Foo { public: int x; int y; // Lexicographic ordering but by the y member first, and by x second. std::strong_ordering operator<=>(const Foo& other) { if (std::strong_ordering cmp = y <=> other.y; cmp != 0) return cmp; return x <=> other.x; } }; int main() { Foo f = {1, 1}, g = {1, 0}; std::cout << (f == g); } which returns error no match for ‘operator==’ (operand types are ‘Foo’ and ‘Foo’). What I want to know is, first of all, WHY DOESN'T operator<=> generate operator== and secondly -- is there a complete list of which operators generate other operators (and which ones), or is that cppreference article complete in that regard and there are no other operators being generated? For instance I'd expect operator+(Foo) and operator-() to generate operator-(Foo), on the basis that subtracting is nothing but adding the additive inverse. This, however, turns out to be untrue, which I also tested.
Which operators implicitly define / generate other operators in C++? There is only one situation in which one operator defines/generates another, and that is when you default operator<=> you also get a defaulted operator==. That's the complete list. Everything else is not based on declaring operators, it is based on rewriting expressions: it's not that an operator!= is generated from operator==, it's that the expression x != y also tries to evaluate as !(x == y) it's not that an operator< is generated from operator<=>, it's that the expression x < y also tries to evaluate as (x <=> y) < 0 In your case, f == g simply has no operator== candidate, so it's ill-formed. The original design of <=> also would try to rewrite this expression as (f <=> g) == 0 (again, not generating operator== but rather rewriting the expression). But this was shown to have serious performance issues and so it was changed to not do this. You can read more about Comparisons in C++20 here. In this case, since you're doing member-wise comparison, you can simply: bool operator==(Foo const&) const = default; or write it manually if you prefer. Either way, your operator<=> is missing a const - it's important that the comparison operators be symmetric.
69,927,137
69,927,258
infinite for loops in c++
I am playing around a little with for loops , tried the following code and got an infinite loop. #include<iostream> int main(){ int i {0}; bool condition = i < 5; for ( ; condition ; ){ std::cout << "Hello World!" << std::endl; i++; } } Can someone explain why ?
bool condition = i < 5; This line defines a variable named condition which has the value true from this line onwards. It does not bind the expression from the right side, but only copies the result at the time of assignment. What you intended is more complicated: auto condition = [&i](){ return i < 5; }; for ( ; condition() ; ) Now condition is a function object which can be evaluated repeatedly. The right hand of the assignment is called a lambda expression, and follows the form [capture scope](parameters){ body with return statement }. In the capture scope, you can list variables either by value (without &) in which case they get copied once when the lambda is declared, or by reference (with leading &) in which case they don't get copied but the variable inside the lambda is a reference to the variable of the same name outside the lambda. There is also the short form [&] which captures all variables in the parent scope by reference, and [=] which captures everything by value. auto can be used for brevity in combined declarations + assignments, and automatically resolves the type of the variable from the right hand side. The closest compatible type you could explicitly specify would be std::function<bool(void)> (generic container for functions with that signature), the actual type of that object is some internal type representing the naked lambda which you can't write explicitly. So if you can't know the exact type, and you don't want to use a generic container type, auto is occasionally even necessary.
69,928,394
69,928,455
Are references / pointers guaranteed to be valid after moving std::deque?
Is it safe to assume that any pointers I have to elements inside of an std::deque are still valid after moving the deque to another one with the move constructor? For std::vector I cannot see any reason why they wouldn't be, but I'm not familiar enough with std::deque to be sure I can make the same assumption.
Pointers to elements would remain valid. After move construction: After container move construction (overload (8)), references, pointers, and iterators (other than the end iterator) to other remain valid, but refer to elements that are now in *this. The current standard makes this guarantee via the blanket statement in [container.requirements.general]/12, and a more direct guarantee is under consideration via LWG 2321.
69,928,760
69,928,870
unable to get the following part in CRC implementation in c++
So i was referring Geeks For Geeks for the implementation of CRC in Data Communication Here is the code:- #include <bits/stdc++.h> using namespace std; string xor1(string a, string b) { string result = ""; int n = b.length(); for (int i = 1; i < n; i++) { if (a[i] == b[i]) result += "0"; else result += "1"; } return result; } string mod2div(string divident, string divisor) { int pick = divisor.length(); string tmp = divident.substr(0, pick); int n = divident.length(); while (pick < n) { if (tmp[0] == '1') tmp = xor1(divisor, tmp) + divident[pick]; else tmp = xor1(std::string(pick, '0'), tmp) + divident[pick]; pick += 1; } if (tmp[0] == '1') tmp = xor1(divisor, tmp); else tmp = xor1(std::string(pick, '0'), tmp); return tmp; } void encodeData(string data, string key) { int l_key = key.length(); string zeroes_to_be_added; for(int i=0;i<l_key-1;i++) zeroes_to_be_added = zeroes_to_be_added + "0"; string appended_data = (data + zeroes_to_be_added); string remainder = mod2div(appended_data, key); string codeword = data + remainder; cout << "Remainder : " << remainder << "\n"; cout << "Encoded Data (Data + Remainder) :" << codeword << "\n"; } int main() { string data,key; cout<<"enter the data to be send to the receiver side from the sender side"<<endl; cin>>data; cout<<"Enter the key value that is present on both sender and reciever side"<<endl; cin>>key; encodeData(data, key); return 0; } i get all the code except the below one :- string mod2div(string divident, string divisor) { int pick = divisor.length(); string tmp = divident.substr(0, pick); int n = divident.length(); while (pick < n) { if (tmp[0] == '1') tmp = xor1(divisor, tmp) + divident[pick]; else tmp = xor1(std::string(pick, '0'), tmp) + divident[pick]; pick += 1; } if (tmp[0] == '1') tmp = xor1(divisor, tmp); else tmp = xor1(std::string(pick, '0'), tmp); return tmp; } could someone can help me in getting to understand this part lets say for the data = 1010101010 and the key = 11001. issue:- What is the use of this like what exactly this part is doing:- std::string(pick, '0') Any help will be appreciated.
std::string(pick, '0') is the string constructor creating a string of length pick filled with '0'. In other ways it's the short form of the following code :- string zeroes_to_be_added; zeroes_to_be_added.resize(pick); for (int i = 0; i < pick; i++) zeroes_to_be_added[pick] = '0';
69,928,789
69,943,207
How to pass value to or call a function of AMyPlayerController (APlayerController) from UMenuWidget (UUserWidget) in Unreal, using C++?
My UMenuWidget (derived from UUserWidget) needs to pass a value to AMyPlayerController (derived from APlayerController). I have tried: DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FPassParam,int,intData); But inGameHUD->MenuWidget from AMyPlayerController::BeginPlay() returns NULL, likely because MenuWidget is yet to be created. This prevents me from add/bind-ing of functions. How can I do/solve this? Kindly help me, please. Thank you.
Link to answer, at UE4 Answer Hub: https://answers.unrealengine.com/questions/1056641/how-to-pass-value-to-or-call-a-function-of-amyplay.html
69,929,010
69,929,358
typeid result in different compilers
I am watching the following video It is mentioned here that g++ will report an error for the following code: #include<vector> #include<typeinfo> #include<iostream> struct S { std::vector<std::string> b ; }; int main() { S s; std::cout << typeid(S::b).name(); } error: invalid use of non-static data member ‘S::b’ But I did not encounter this kind of error under msvc and clang. Who is right and why? And why is it changed to typeid(&S::b).name(); Is the result correct afterwards?
Gcc is wrong (Bug 68604). S::b is an id-expression referring to a non-static data member, which could be used only in unevaluated context. Gcc seems failing in taking this as unevaluated expression. As the workaround you could: std::cout << typeid(decltype(S::b)).name(); Note that in typeid(&S::b).name();, &S::b gives a pointer to member; the result is different with using S::b.
69,929,238
69,929,353
While loop not breaking?? C++
I'm trying to construct a simple dice game in C++. I do not understand why it's not breaking out of the while loop. You are supposed to ONLY be able to bet 100, 300, or 500€. Even if I enter my bet "100-300-500" which is supposed to be correct. It still loops and says it's an invalid bet. Why doesn't it progress to the if statement when I have if ((bet1 == 100) || (bet1 ==300) || (bet1==500)) I've tried putting the if statement before the while loop and all sorts of things. I can't get it to work. cout << "Please place a bet. 100, 300, 500kr" << endl; cin >> bet1; while ((bet1 <= 99) || (bet1 >= 101) || (bet1 <= 299) || (bet1 >= 301) || (bet1 <= 499) || (bet1 >= 501)) { cout << "Please place a valid bet" << endl; cin >> bet1; } if ((bet1 == 100) || (bet1 ==300) || (bet1==500)) { cout << "You have deposited " << " " << bet1 << "" << "And you now have: "<< saldo - bet1 << " " << "Remaining on your account." << endl; }
This loop while ((bet1 <= 99) || (bet1 >= 101) || (bet1 <= 299) || (bet1 >= 301) || (bet1 <= 499) || (bet1 >= 501)) { cout << "Please place a valid bet" << endl; cin >> bet1; } is an infinite loop for any valid entered value 100, 300 or 500. For example if the user will enter 100 then at least this condition (bet1 <= 299) evaluates to true. If the user will enter 300 then at least this condition (bet1 >= 101) evaluates to true. If the user will enter 500 then at least again this condition (bet1 >= 101) evaluates to true. You should rewrite the while loop for example like while ( bet1 != 100 && bet1 != 300 && bet1 != 500 ) { cout << "Please place a valid bet" << endl; cin >> bet1; } Using your approach to writing the loop the condition can look like while ( ( bet1 <= 99 ) || ( bet1 >= 101 && bet1 <= 299 ) || (bet1 >= 301 && bet1 <= 499 ) || ( bet1 >= 501 ) ) { cout << "Please place a valid bet" << endl; cin >> bet1; }
69,929,810
69,929,874
"error: duplicate case value" error when using goto in switch statement
I was trying to use the goto statement to travel between different switch-cases. I understand, it's not preferable to use goto as it would make the program tough to understand, but I really need it. Here's the example version of my code: switch(something){ case "c1": //some code break; case "c2": //some code break; case "c3": if(condition1) goto case "c1"; if(condition2) goto case "c2"; default: break; } Now, when I run the code, I get the following error error: duplicate case value which applies to both goto case "c1" and goto case "c2". I'm not sure why the compiler is thinking the goto on a switch-case is redefining another case in the switch statement with the same condition and hence throwing that duplicate error. Any help and reasons for this error is appreciated. Thanks!
In any case the switch statement does not make a sense because you are using string literals as case labels. switch(something){ case "c1": //some code break; case "c2": //some code break; case "c3": if(condition1) goto case "c1"; if(condition2) goto case "c2"; default: break; } The expression in the switch statement is converted to an integral or enumeration type that can not be implicitly converted to pointers or string literals. Maybe you need to use character literals as for example case 'c1': The second problem is you may not use case labels with goto statements. You may use with the goto statements only labels that are presented as identifiers. The syntax of the goto statement is goto identifier ; So the compiler thinks that the case labels used in goto statements redefine already introduced case labels.
69,930,155
69,930,873
Initialize members at later point without using pointers possible? C++
Say I have a class A, that consumes messages of a network. Class A has 2 members b and c of corresponding type B and C. The members can only be initialized with information, that comes from the network. Is there a way to initialize the members at a later point, without having the members to be of type B* and C* (initialize with nullptr and set the wanted value later)? I feel like in such a scenario the design has a flaw, but I am still asking myself what the best practice would be, as I am kind of sluggish when using pointers after reading Why should I use a pointer rather than the object itself? ?
std::optional<T> is a "nullable" wrapper around a type T. It acts a bit like a pointer in syntax, but there is no dynamic allocation. std::optional<int> bob; if (bob) // is there anything in the box? std::cout << *bob; // print what is in the box. You can do: bob = 7; // Assign 7 to what is in `bob`, or construct with a 7. bob.emplace(3); // construct the contents of `bob` with the value 3 When reading, you can do: std::cout << bob.value_or(-1); which either prints the value in bob, or (a T constructed from) -1 if there is nothing there.
69,930,162
69,930,413
I have problem in terms of changing integer into character
This the Instruction I add some photo of the instruction. But my prof wanted to change integer into character. how will I do it? this is my code. I use my full potential in programming but this program makes me down. I use all resources i may find but I didn't get the right code #include <stdlib.h> #include <iostream> using namespace std; int array[10]; void DisplayArray() { for (int i = 0; i < 10; i++) cout << "Array [ " << i << " ] = " << array[i] << endl; } void SetDefaultValues() { cout << "Defalut Values :" << endl; for (int i = 0; i < 10; i++) { array[i] = -1; cout << "array [" << i << "]" << "= " << array[i] << endl; } } void InsertValues() { cout << "Enter 10 Values " << endl; for (int i = 0; i < 10; i++) { cin >> array[i]; } cout << "\n\t\t\tArray Values Inserted... Successfully " << endl; } void DeleteValues() { cout << "Enter the Index Number To Delete Value :"; int index; cin >> index; if (index > 9 || index < 0) { cout << "Invalid Index Entered-> Valid Range(0-9)" << endl; DeleteValues(); // Recall The Function it self } else { array[index] = -1; } cout << "\n\t\t\tArray Value Deleted... Successfully " << endl; } void UpdateValues() { cout << "Enter Index Number to Update Value :"; int index; cin >> index; if (index > 9 || index < 0) { cout << "Invalid Index Entered-> Valid Range(0-9)" << endl; UpdateValues(); // Recall The Function it self } else { cout << "Enter the New Value For Index array[ " << index << " ] = "; cin >> array[index]; cout << "\n\t\t\tArray Updated... Successfully " << endl; } } int main() { char option; SetDefaultValues(); do { cout << "\t\t\tEnter 1 to Enter Values\n\t\t\tEnter 2 to Update " "Values\n\t\t\tEnter 3 to Delete Values\n\n\t\t\t or Enter E to " "EXIT\n\n\t\t\t Enter Option: -> "; cin >> option; if (option == '1') { cout << "Insert Function Called" << endl; InsertValues(); cout << "Inserted Values :" << endl; DisplayArray(); } else if (option == '2') { UpdateValues(); cout << "Updated Array :" << endl; DisplayArray(); } else if (option == '3') { DeleteValues(); cout << "Array After Deleting Values :" << endl; DisplayArray(); } else if (option != 'e' && option != 'E') { cout << "\n\n\t\t\tSelect A Valid Option From Below\n\n"; } } while (option != 'e' && option != 'E'); system("cls"); // To Clear The Screen cout << "\n\n\n\n\n\n\n\n\n\n\t\tProgram Ended Press Any Key To Exit " "Screen.....\n\n\n\n\n\n\n\n\n\n\n\n" << endl; return 0; } This is the output of my current program Defalut Values : array [0]= -1 array [1]= -1 array [2]= -1 array [3]= -1 array [4]= -1 array [5]= -1 array [6]= -1 array [7]= -1 array [8]= -1 array [9]= -1 Enter 1 to Enter Values Enter 2 to Update Values Enter 3 to Delete Values or Enter E to EXIT Enter Option: ->
the first really necessary change is to move int array[10]; to char array[10]; in that way we can store characters instead of store integers. since your program is using std::cout and std::cin (and both of them got different overloads getting a char or an integer) you don't really need to change nothing else except the default value (-1) which is an invalid character. You may use basically a dot ('.') as default value or anything else that looks good to you. About the search option you can basically loop trought the array and print what positions match. void SearchCharacter(char a){ bool printed_out = false; for(unsigned int i=0; i < sizeof(array)/sizeof(array[0]); ++i){ if(array[i] == a){ if(!printed_out){ std::cout << "The character " << a << " is found in position: "; printed_out = true; } std::cout << i << " "; } } if(printed_out) std::cout << std::endl; else std::cout << "No matches found for character: " << a << std::endl; }
69,930,528
69,931,048
Is it allowed to emit a signal trough a pointer to an instance of another class?
Minimal example: class Foo : public QObject { Q_OBJECT signals: void TestSignal(int i) const; }; class Bar : public QObject { Q_OBJECT public: Bar(Foo* foo) : mFoo{ foo } {} void TestEmit(int i) const { emit mFoo->TestSignal(i); } private: Foo* mFoo; }; void Print(int i) { std::cout << i << std::endl; } Usage: Foo aFoo; Bar aBar{ &aFoo }; connect(&aFoo, &Foo::TestSignal, &Print); aBar.TestEmit(1337); So I'm emitting the signal Foo::TestSignal from function Bar::TestEmit using a pointer to a Foo instance. This seems to work fine, but is it allowed ? (as in: reliable defined behavior).
From https://doc.qt.io/qt-5/signalsandslots.html : Signals are public access functions and can be emitted from anywhere, but we recommend to only emit them from the class that defines the signal and its subclasses I understand it is technically allowed and reliable but not recommended in terms of code design. You might also be interested to connect a signal to another as explained here https://doc.qt.io/qt-5/qobject.html#connect
69,930,782
69,930,881
c++ read binary data from istream
I have an istream and I have to read it into a buffer. I could not find a way to figure out the read_len once eof is encountered? I cannot use get because my file does not have delimeters. It seems that the only option is to read it character by character, is it really the only option? char buffer[128]; while(is.good()) { is.read(buffer, sizeof(buffer)); size_t read_len = sizeof(buffer); if (is.eof()) { read_len = xxxx; } process(buffer, read_len); }
You could check istream::gcount() which "Returns the number of characters extracted by the last unformatted input operation". Example: while(is) { is.read(buffer, sizeof buffer); auto read_len = is.gcount(); // <- if(read_len > 0) process(buffer, read_len); else break; } You could also use istream::readsome() - but note: "The behavior of this function is highly implementation-specific." which may or may not be an issue.
69,931,435
69,931,941
How do I properly set the precision of std::complex<mpf_class> and read it in?
I wanted to have an std::complex<mpf_class> with a specific precision (400), and read in the complex from std::cin. I didn't know how to set the precision in the declaration of the complex, so I tried this first: std::complex<mpf_class > c; c.real().set_prec(400); c.imag().set_prec(400); std::cin >> c; std::cout << std::setprecision(400) << c; But with the input (0.12345678123456781234567812345678,0), I got the output (0.123456781234567812346,0). This isn't right because 400 bits of precision should be able to hold all the digits of the input. I wanted to make sure that std::complex could hold higher precision variables so I tried this: mpf_class a(0, 400); mpf_class b(0, 400); std::cin >> a >> b; std::complex<mpf_class> c(a, b); std::cout << std::setprecision(400) << c; With the same input, 0.12345678123456781234567812345678 0, the output was (0.12345678123456781234567812345678,0). So it held all the digits, but I had to both declare and read the complex parts first; not ideal. But I was still trying to figure out what was causing the first code segment to not work. One difference I noticed between the first two code segments was that the precision in the first was set after the declaration of the mpf_class, while the second segment sets the precision during the mpf_class declaration. I just wanted to check that you could update the precision of an mpf_class so I tried this: mpf_class a(0, 32); a.set_prec(400); std::cin >> a; std::cout << std::setprecision(400) << a; With the input 0.12354678123456781234567812345678, the output was the same which means the precision can be updated. Finally I thought there might be some issue with the complex stream extraction operator and high precision decimals. So I set the precision of the mpf_class before declaring the complex, then declared the complex, then read in the complex: mpf_class a, b; a.set_prec(400); b.set_prec(400); std::complex<mpf_class> c(a, b); std::cin >> c; std::cout << std::setprecision(400) << c; But with this the weirdest thing happened. With input (0.12345678123456781234567812345678,0) the output was (0.1234567812345678123456781234567799999999999999999999999999273060010609330153935727917471428455421640301869890510557285753902098601227437,0) TLDR There are three steps to reading in a high precision complex: set precision, read values, declare complex. These steps can be permutated in a variety of orders. Obviously the setting of the precision has to be done before reading the values. But then there are still three different orderings with three different behaviors. Code segment 1 shows that the ordering of (declare complex, set precision, read values) doesn't work because the precision didn't get updated. Code segment 2 shows that the ordering of (set precision, read values, declare complex) works as expected, but is inconvenient because you have to declare the complex components separately. Finally code segment 4 shows that the ordering of (set precision, declare complex, read values) introduces weird rounding errors. My questions are these: Can anyone explain these discrepancies? How can I declare an std::complex<mpf_class> with a given precision?
Thanks to pasaba por aqui for explaining why the first code segment doesn't work. I have thought about it a little more and decided this might be an appropriate solution: std::complex<mpf_class> c (mpf_class(0,400), mpf_class(0,400)); std::cin >> c; std::cout << std::setprecision(400) << c; This code segment properly sets the precision of the complex's individual parts without having to declare the individual parts before hand. However, it still doesn't solve the weird rounding error problem that we saw in the OP code segment 4. If anyone has a better solution to the OP or can explain how the rounding error is introduced/how to avoid it, please comment or submit a new answer. I will keep this post open for a couple days and if I don't see anything else I will accept this answer as the answer to the OP.
69,931,451
70,185,995
How to play avi video using GStreamer
I am trying to play my first video in GSTreamer, by using GstElement, without pre-configured things like gst_parse_launch etc I dont understand why my pipeline cant be linked and I get an error "unable to set the pipeline to playing state" ? How can I fix it? What is missed? #include <iostream> #include <gst/gst.h> int main(int argc, char *argv[]) { GstElement *pipeline; GstElement *source, *sink; gst_init(&argc, &argv); //! Initialize GStreamer pipeline = gst_pipeline_new("my-pipeline"); //! Creating pipeline source = gst_element_factory_make("filesrc", "file-source"); //! Creating source g_object_set(G_OBJECT(source), "location", "file:///D:/workspace/rocket.mp4", NULL); sink = gst_element_factory_make("autovideosink", "sink"); //! Creating sink if (sink == NULL) { g_error("Could not create neither 'autovideosink' element"); } gst_bin_add_many(GST_BIN(pipeline), source, sink, NULL); //! Adding elements to pipeline container if (!gst_element_link_many(source, sink, NULL)) //! Linking all elements together { g_warning("Unable to link elements!"); } auto ret = gst_element_set_state(pipeline, GST_STATE_PLAYING); //! Turning pipeline in PLAYING STATE if (ret == GST_STATE_CHANGE_FAILURE) { g_printerr("unable to set the pipeline to playing state"); gst_object_unref(pipeline); return -1; } return 0; } Thanks in advance!
Here is an answer First of all, here is github link to my solution with comments. Explanation: If you want to play video file, without predefined pipelines, like playbin, gst_parse_launch etc, you have two options Dynamically link uridecodebin with 2 pipeline sleeves (one for audio and second for video) Dynamically link by using avidemux and make it on 'atomic' level. Its very complicated, and there is no working help in net. Maybe I will update this branch later with working solution. In my github link, you will find first solution with 2 pipelines and uridecodebin
69,931,678
69,932,122
C++ Iterate over template variable instantiations
Take a look at this: #include <vector> #include <iostream> template<class T> std::vector<T> vec{}; int main() { vec<short>.push_back(5); vec<int>.push_back(10); vec<long int>.push_back(15); } The vec variable is templated, but there is no telling what possible instantiations occurred. In this case it is clear: short, int and long. But what about more complex cases? How do I track template instantiations? My goal is to be able to iterate over all vec instances. Something like for (std::any element : vec) { delete element; // Or any common logic the types might have (can guarantee with concepts) }
You might be able to do something if you wrap vec in a function, and have a type-erased "do things to vec<T>" interface. You will need to specify all the things you want to do to the various vec<T>()s up front. template <typename T> concept printable = requires (T t) { std::cout << t; } template <printable T> std::vector<T> & vec(); struct vec_printer { vec_printer(std::type_index index) : index(index) {} virtual ~vec_printer() = default; virtual void print() = 0; // etc... std::type_index index; }; struct vec_printer_compare { using ptr = std::unique_ptr<vec_printer>; bool operator(const ptr & lhs, const ptr & rhs){ return lhs->index < rhs->index; } }; std::set<std::unique_ptr<vec_printer>, vec_printer_compare> vec_printers; template <printable T> struct vec_printer_impl { vec_printer_impl() : vec_printer(typeid(T)) {} void thing_one() { for (auto & v : vec<T>()) { std::cout << v; } } }; template <printable T> std::vector<T> & vec() { vec_printers.emplace(std::make_unique<vec_printer_impl<T>>()); static std::vector<T> v; return v; } void print_vecs() { for (auto & printer : vec_printers) { printer->print(); } }
69,931,685
69,932,099
2 questions about cppreference.com's explanation of decltype
When I was reading this online c++ reference page about decltype I was wondering about this paragraph: If expression is a function call which returns a prvalue of class type or is a comma expression whose right operand is such a function call, a temporary object is not introduced for that prvalue. (until C++17) My question is: Introducing or not introducing a temporary, does that matter? And this paragraph: Note that if the name of an object is parenthesized, it is treated as an ordinary lvalue expression, thus decltype(x) and decltype((x)) are often different types. And again my question: What's the rationale behind treating them differently? Can anyone out there give me a hand and shed some light on the dark corners I'm in. Thanks.
Introducing or not introducing a temporary, does that matter? This makes a bit more sense if you look at an expression that uses the result of a function: // given template<typename T> struct Foo {}; template<typename T> Foo<T> foo(); template<typename T> void bar(const Foo<T>&); // This: bar(foo<int>()); // Is equivalent to: { Foo<int>&& tmp = foo<int>(); bar(tmp); } // So should tmp "exist" here? using T = decltype(foo<int>()); You could easily argue that the foo<int>() expression actually is equivalent to Foo<int>&& tmp = foo<int>(). If the existence of tmp was somehow undesirable in a decltype() context, then it needs to be made clear. And tmp is definitely undesirable here. It causes the Foo<int> specialization to be created. But just because you have identified a type does not mean you are actually using it. The same goes for type aliases. Demonstration: (see on godbolt) #include <type_traits> template<typename T> struct Foo { // Will cause a compile error if it's ever instantiated with int static_assert(!std::is_same_v<T, int>); }; using FooInt = Foo<int>; template<typename T> Foo<T> foo() { return {}; } void bar() { // Does not cause Foo<int> to exist just yet using T = decltype(foo<int>()); // This instantiates Foo<int> and causes the compile error // T x; } What's the rationale behind treating them differently? N.B. This following is more of a guideline for how to reason about this. The actual technical details are different, but it can get rather convoluted. Don't think of it as the parentheses being anything special. Instead, think of it as decltype(id-expression) being the special case. Let's say we have the following declaration: int x; The x expression does not behave like an int, but a int& instead. Otherwise x = 3; wouldn't make sense. Despite that, decltype(x) is still int. That's the special case: decltype(id-expression) returns the type of the identifier itself instead of the type of the expression. On the other hand, (x) also behaves like int&, but since it's not an id-expression, it gets interpreted as just any regular expression. So decltype((x)) is int&. #include <type_traits> int x = 0; using T = decltype(x); using U = decltype((x)); static_assert(std::is_same_v<T, int>); static_assert(std::is_same_v<U, int&>);
69,931,864
69,935,936
Concept to keep track of class instantiations in C++
I am trying to write a code that keeps track of instances of my class. Each instance is uniquely identified by a type (int). I would like to have some kind a map which links a type to a instantiation of my class. My idea was to use a static map for this, and every instantiation registers itself when the constructor is called: #include <unordered_map> #include <iostream> class Dummy { public: Dummy(double a, double b, double c, int type); void GetContents() {std::cout << type_ <<": a: " << a_ << " b: " << b_ << ", c: " << c_ << std::endl;} private: const double a_; const double b_; const double c_; const int type_; }; static std::unordered_map<int, Dummy> Type_Map{{12, Dummy(1, 2, 3, 12)}}; // pre-defined instantiation Dummy::Dummy(double a, double b, double c, int type) : a_(a), b_(b), c_(c), type_(type) { Type_Map.insert({type, *this}); }; In this case, everything seems to work well: int main() { Dummy(12, 6, 23, 3); Dummy(8, 22, -4, 7); for (auto a : Type_Map) { std::cout << a.first << ", "; a.second.GetContents(); } } which gives a correct output: 3, 3: a: 12 b: 6, c: 23 7, 7: a: 8 b: 22, c: -4 12, 12: a: 1 b: 2, c: 3 However, outside of this minimal example and in my real-life project, this seems to be unstable. While the instantiation is still registered in the map inside of the constructor, the map entry is lost as soon as I leave the constructor. I believe this may have to do with the *this call inside the constructor where the object is not yet correctly initialized? Is this ill-defined behavior? Is there a better concept that achieves what I want to do? PS: What I actually need The code is written this way because I have some instantiations of my StaticData class and many instantiations of my DynamicData class. The content of StaticData instantiations do not change (all members are const), and there are only a few instantiations (this corresponds to the Dummy class in my minimal example). However, there are a lot of DynamicData instantiations. For every DynamicData instantiation, there is a specific StaticData object which belongs to it. I want to avoid that every DynamicData object has to carry a StaticData object. Therefore, it only carries an id that links it uniquely to a StaticData object. If the user wants to find out which StaticData belongs to my specific DynamicData object, we can just look in the map (this will not happen regularly during runtime, but we still need to keep the information). The obvious solution would be to just use pointers. However, I want the user to be able to just initialize a DynamicData object with the id instead of having to pass a pointer to a StaticData object.
Your problem is that the static map is filled inside the constructor, but outside of the constructor, the entry is gone. It seems like there are two different instances of the static map. You see one instance inside the constructor, and another instance outside of the constructor. It looks like, you define your static map in a header file. Each .cpp file that includes the header file will "see" its own instance of the static map. Solution: Make a class which keeps the map as a static member. If this does not solve your problem, make also sure that you define the static member inside a .cpp file, like: map<int, Dummy> TypeRegistry::Type_Map;
69,931,954
70,075,669
c++ read map in binary file which created in python
I created a Python script which creates the following map (illustration): map<uint32_t, string> tempMap = {{2,"xx"}, {200, "yy"}}; and saved it as map.out file (a binary file). When I try to read the binary file from C++, it doesn't copy the map, why? map<uint32_t, string> tempMap; ifstream readFile; std::streamsize length; readFile.open("somePath\\map.out", ios::binary | ios::in); if (readFile) { readFile.ignore( std::numeric_limits<std::streamsize>::max() ); length = readFile.gcount(); readFile.clear(); // Since ignore will have set eof. readFile.seekg( 0, std::ios_base::beg ); readFile.read((char *)&tempMap,length); for(auto &it: tempMap) { /* cout<<("%u, %s",it.first, it.second.c_str()); ->Prints map*/ } } readFile.close(); readFile.clear();
It's not possible to read in raw bytes and have it construct a map (or most containers, for that matter)[1]; and so you will have to write some code to perform proper serialization instead. If the data being stored/loaded is simple, as per your example, then you can easily devise a scheme for how this might be serialized, and then write the code to load it. For example, a simple plaintext mapping can be established by writing the file with each member after a newline: <number> <string> ... So for your example of: std::map<std::uint32_t, std::string> tempMap = {{2,"xx"}, {200, "yy"}}; this could be encoded as: 2 xx 200 yy In which case the code to deserialize this would simply read each value 1-by-1 and reconstruct the map: // Note: untested auto loadMap(const std::filesystem::path& path) -> std::map<std::uint32_t, std::string> { auto result = std::map<std::uint32_t, std::string>{}; auto file = std::ifstream{path}; while (true) { auto key = std::uint32_t{}; auto value = std::string{}; if (!(file >> key)) { break; } if (!std::getline(file, value)) { break; } result[key] = std::move(value); } return result; } Note: For this to work, you need your python program to output the format that will be read from your C++ program. If the data you are trying to read/write is sufficiently complicated, you may look into different serialization interchange formats. Since you're working between python and C++, you'll need to look into libraries that support both. For a list of recommendations, see the answers to Cross-platform and language (de)serialization [1] The reason you can't just read (or write) the whole container as bytes and have it work is because data in containers isn't stored inline. Writing the raw bytes out won't produce something like 2 xx\n200 yy\n automatically for you. Instead, you'll be writing the raw addresses of pointers to indirect data structures such as the map's internal node objects. For example, a hypothetical map implementation might contain a node like: template <typename Key, typename Value> struct map_node { Key key; Value value; map_node* left; map_node* right; }; (The real map implementation is much more complicated than this, but this is a simplified representation) If map<Key,Value> contains a map_node<Key,Value> member, then writing this out in binary will write the binary representation of key, value, left, and right -- the latter of which are pointers. The same is true with any container that uses indirection of any kind; the addresses will fundamentally differ between the time they are written and read, since they depend on the state of the program at any given time. You can write a simple map_node to test this, and just print out the bytes to see what it produces; the pointer will be serialized as well. Behaviorally, this is the exact same as what you are trying to do with a map and reading from a binary file. See the below example which includes different addresses. Live Example
69,932,096
69,932,257
Attempting to delete an initializer list constructor does not always take effect
Sorry for the generic title, but it's a mindfu*k situation, which I can't easily describe. Suppose the following code: struct S { S() = default; int x; int y; }; S f() { return { 1, 2 }; } This compiles and works perfectly fine. I want to forbid it, as it's bug prone (the actual code is far more complex). So, I tried adding template<typename T> S(std::initializer_list<T>) = delete; but guess what - nothing changes. Tested on Visual Studio 2019 with std=c++17. The C++ resharper shows this as an error, but msvc actually compiles this and it works. Wait, now it gets interesting. If S() = default; is replaced with S() {}, the compilation fails with 'S::S<int>(std::initializer_list<int>)': attempting to reference a deleted function OK, this looks like something to do with user-defined constructors and initialization?! Messy, but kinda understandable. But wait - it gets even more interesting - keeping the = default constructor, but making the fields private also alters this behavior and guess what - the error has nothing to do with inaccessible members, but it again shows the error from above! So, in order to make this deletion work, I should either make the fields private or define my own empty constructor (ignore the uninitialized x and y fields, this is just a simplified example), meaning: struct S { S() = default; // S() {} template<typename T> S(std::initializer_list<T>) = delete; private: int x; int y; }; clang 13 and GCC 11 behave exactly the same way, while GCC 9.3 fails to compile the original code (with =default constructor, public fields, but deleted initializer list constructor). Any ideas what happens?
In C++17, S is considered an aggregate, and because of that you are not calling any constructor, you are basically directly initializing the members. If you change to using C++20, S is no longer considered an aggregate as the rules were changes and the code will work as expected. The reason changing the access specifier works is that the access specifier of all non-static data members of an aggregate needs to be public. Having them be non-public means your class is no longer an aggregate, and you no longer get aggregate initialization, but instead it tries to do list initialization and fails for the deleted constructor.
69,932,590
69,932,820
Default reference parameters and lifetimes in coroutines
I'm confused about the lifetime of parameters passed to C++ coroutines. Answering to a previous question, smart people stated that The lifetime of a parameter is [...] part of the caller's scope Now, to follow up, what happens when passing default arguments like generator my_coroutine(string&& s = string()) {...} So, if my_coroutine was a normal function, s would be valid throughout its scope. However, this seems to no longer hold if my_coroutine is a coroutine. In particular the results of the following coroutine-test surprised me: #include <iostream> #include <coroutine> struct Test { int i = 3; Test() { std::cout << "test constructed\n";} Test(const Test&) = delete; Test(Test&&) = delete; ~Test() { std::cout << "test destructed\n"; } friend std::ostream& operator<<(std::ostream& os, const Test& t) { return os << t.i; } }; template<class T> generator<int> coro_test(T&& t = T()) { int i = 0; while(i++ < 3) co_yield i; if(i == t.i) co_yield 100; } int main () { auto gen = coro_test<Test>(); while(gen.is_valid()) { std::cout << *gen << "\n"; ++gen; } return 0; } results: test constructed test destructed 1 2 3 PS: for completeness, here's my generator: template<class T> struct generator { struct promise_type; using coro_handle = std::coroutine_handle<promise_type>; struct promise_type { T current_value; auto get_return_object() { return generator{coro_handle::from_promise(*this)}; } auto initial_suspend() const noexcept { return std::suspend_never{}; } auto final_suspend() const noexcept { return std::suspend_always{}; } void unhandled_exception() const { std::terminate(); } template<class Q> auto yield_value(Q&& value) { current_value = std::forward<Q>(value); return std::suspend_always{}; } }; private: coro_handle coro; generator(coro_handle h): coro(h) {} public: bool is_valid() const { return !coro.done(); } generator& operator++() { if(is_valid()) coro.resume(); return *this; } T& operator*() { return coro.promise().current_value; } const T& operator*() const { return coro.promise().current_value; } generator(const generator&) = delete; generator& operator=(const generator&) = delete; ~generator() { if(coro) coro.destroy(); } };
As pointed out in said "previous question", the first thing that happens in a coroutine is that parameters are "copied" into storage owned by the coroutine. However, the "copy" is ultimately initialized based on the type declared in the signature. That is, if a parameter is a reference, then the "copy" of that parameter is also a reference. So a coroutine function that takes reference parameters is much like any kind of asynchronous function that takes reference parameters: the caller must ensure that the referenced object continues to exist throughout the time that the object will be used. A default parameter which initializes a reference is a circumstance that the caller cannot control the lifetime of (other than providing an explicit parameter). You created an API that is inherently broken. Don't do that. Indeed, it's best to avoid passing references to async functions of any kind, but if you do, never give them default parameters.
69,932,704
69,932,891
how to use find_if to find element in given vector of pairs
For example consider vector<pair<string,int>> And it contains: ABC 1 BCD 2 CDE 3 XHZ 4 string s; cin>>s; if(find_if(vec.begin(),vec.begin()+3,cmp)!=vec.begin()+3) // I want to check only first 3 values I need cmp to find given string is present or not using find_if EDIT: How to pass the string s with the comparator (cmp) and the vector will always contains minimum 3 elements
The simplest way is to use a lambda expression. For example #include <string> #include <utility> #include <vector> #include <iterator> #include <algorithm> //... std::string s; std::cin >> s; auto cmp = [&s]( const auto &p ) { return p.first == s; }; if ( std::find_if( std::begin( vec ), std::next( std::begin( vec ), 3 ), cmp ) != std::next( std::begin( vec ), 3 ) ) { //... } Another approach is to create a function object before main as for example class cmp { public: cmp( const std::string &s ) : s( s ) { } bool operator() ( const std::pair<std::string, int> &p ) const { return p.first == s; } private: const std::string &s; }; //... if ( std::find_if( std::begin( vec ), std::next( std::begin( vec ), 3 ), cmp( s ) ) != std::next( std::begin( vec ), 3 ) ) { //... }
69,932,934
69,933,068
Why is GLM Perspective projection acting like Orthographic Projection
I Have a projection matrix in my C++ OpenGL Application. glm::mat4 projection = glm::perspective(45.0f, 16.0f / 9.0f, 1.0f, 100.0f); This Matrix is later sent as uniform to the Vertex Shader -> Nade::Shader::SetMat4(app.shader->GetProgram(), "p", app.projection); And Utilized inside the Vertex Shader gl_Position = m * p * vec4(pos,1.0); And then the Rendered Quad is moved at the Z Axis object.Translate(0, 0, -0.05); Observed Behavior: The Rendered Mesh behaves like it is within a Orthographic Matrix where it stays same in size but clips away at the far point Expected Behavior: The Rendered Mesh reduces in size and clips away. How can I fix this?
gl_Position = m * p * vec4(pos,1.0); is equivalent to gl_Position = m * (p * vec4(pos,1.0));, which means that the position is transformed by p before being transformed by m. Assuming p means "projection" and m means "modelview", then it should be: gl_Position = p * m * vec4(pos,1.0); You might be wondering: Why didn't this cause issues earlier? With an orthographic projection, and a camera looking down the z axis, the original code could still look like it works. That's because a zero-centered orthographic projection is basically just a scaling matrix.
69,933,305
69,933,423
Convert decimal to binary and let binary length always eight using C++
I need a way to convert a decimal number into a binary number in c++, but the problem is, that the length of the binary number always has to be 8bit. Is there a way to do this? I already did a conversion like this, but the length is not always 8bits: int DecimalToBinary(int decimal) { int binary = 0; int count = 1; while (decimal != 0) { int res = decimal % 2; decimal /= 2; binary += res * count; count *= 10; } return binary; } Here is a little example of what I want to get as output: This is what I get: 255 > 11111111 5 -> 101 This is what I want: 255 -> 11111111 5 -> 00000101
Note that you're not converting decimal to binary, you're converting to another decimal number of which the output mimics a binary number. (for value five you're really outputting value one-hundered-and-one) But you can use std::bitset to get the output you want : #include <bitset> #include <iostream> int main() { // sets of 8 bits std::bitset<8> twofivefive{ 255 }; std::bitset<8> five{ 5 }; // output : 11111111 std::cout << twofivefive.to_string() << "\n"; // output : 00000101 std::cout << five.to_string() << "\n"; return 0; }
69,933,653
69,938,519
I don't have the proper gstreamer dll loaded for C++ opencv camera capture
I have successfully capture the webcam using Python and opencv but now I am getting back into C++ and trying to do the same simple functionality. Here's my (trimmed down) code: #include <iostream> #include <opencv2\opencv.hpp> #include <opencv2\imgcodecs.hpp> using namespace cv; using std::cout; using std::endl; using std::string; int main() { Mat img; VideoCapture cam(0); if (cam.isOpened()) { cout << "Camera is opened." << endl; } else { cout << "Camera is NOT opened." << endl; } const string camWin{ "Rufus' Webcam" }; namedWindow(camWin); while (1) { cam >> img; imshow(camWin, img); if (waitKey(1) == 27) break; } cam.release(); } This is the error I get when I run: attempting to open the camera using opencv. [ INFO:0] global C:\build\master_winpack-build-win64-vc15\opencv\modules\videoio\src\videoio_registry.cpp (191) cv::`anonymous-namespace'::VideoBackendRegistry::VideoBackendRegistry VIDEOIO: Enabled backends(7, sorted by priority): FFMPEG(1000); GSTREAMER(990); INTEL_MFX(980); MSMF(970); DSHOW(960); CV_IMAGES(950); CV_MJPEG(940) [ INFO:0] global C:\build\master_winpack-build-win64-vc15\opencv\modules\videoio\src\backend_plugin.cpp (370) cv::impl::getPluginCandidates Found 2 plugin(s) for GSTREAMER [ INFO:0] global C:\build\master_winpack-build-win64-vc15\opencv\modules\videoio\src\backend_plugin.cpp (175) cv::impl::DynamicLib::libraryLoad load C:\Users\rufuss\source\repos\OpenCVinCPP\x64\Debug\opencv_videoio_gstreamer450_64d.dll => FAILED [ INFO:0] global C:\build\master_winpack-build-win64-vc15\opencv\modules\videoio\src\backend_plugin.cpp (175) cv::impl::DynamicLib::libraryLoad load opencv_videoio_gstreamer450_64d.dll => FAILED [ INFO:0] global C:\build\master_winpack-build-win64-vc15\opencv\modules\videoio\src\backend_plugin.cpp (370) cv::impl::getPluginCandidates Found 2 plugin(s) for MSMF [ INFO:0] global C:\build\master_winpack-build-win64-vc15\opencv\modules\videoio\src\backend_plugin.cpp (175) cv::impl::DynamicLib::libraryLoad load C:\Users\rufuss\source\repos\OpenCVinCPP\x64\Debug\opencv_videoio_msmf450_64d.dll => OK [ INFO:0] global C:\build\master_winpack-build-win64-vc15\opencv\modules\videoio\src\backend_plugin.cpp (236) cv::impl::PluginBackend::PluginBackend Video I/O: loaded plugin 'Microsoft Media Foundation OpenCV Video I/O plugin' Camera is opened. (basically it doesn't find: opencv_videoio_gstreamer450_64d.dll, because it doesn't exist, so not a path problem) I could use some help either: Installing the missing dll: opencv_videoio_gstreamer450_64d.dll properly. or Disabling gstreamer from the opencv search list. Either would help me, but I'd actually like to know both techniques, for future reference.
You may try adding cam.open(0, CAP_DSHOW); #include <iostream> #include <opencv2\opencv.hpp> #include <opencv2\imgcodecs.hpp> using namespace cv; using std::cout; using std::endl; using std::string; int main() { Mat img; VideoCapture cam; cam.open(0, CAP_DSHOW); if (cam.isOpened()) { cout << "Camera is opened." << endl; } else { cout << "Camera is NOT opened." << endl; } const string camWin{ "Rufus' Webcam" }; namedWindow(camWin); while (1) { cam >> img; imshow(camWin, img); if (waitKey(1) == 27) break; } cam.release(); } If you would like to learn more please see this. Also you could do cmake -DWITH_GSTREAMER=OFF while building, to disable gstreamer. (see this)
69,933,894
69,941,311
Function to invert Eigen matrix without branching statements for auto differentiation
I need to invert an Eigen matrix (9x9 in my particular case) as a part of code that I want to automatically differentiate using CppAD. For this to succeed the code executing the inversion can not contain any branching like for example if or switch statements. Unfortunately, the inverse function of Eigen contains branching with makes the algorithmic differentiation of CppAD fail. Mathematically it should be possible to come up with a formulation that does not need branching for a fixed matrix size that is guaranteed to be invertible. Is that correct? Do you know of any library that implements such an inverse without branching?
There is a mechanical conversion from branch to no-branch for arithmetic functions. Duplicate all the variables you use in each branch, and calculate both halves. At the end of the block, multiply the if branch by condition, and the else branch by !condition, then sum them. Similarly for a switch, calculate all the cases, and multiply by value == case. E.g. Mat frob_branch(Mat a, Mat b) { if (a.baz()) { return a * b; } else { return b * a; } } becomes Mat frob_no_branch(Mat a, Mat b) { auto if_true = a * b; auto if_false = b * a; bool condition = a.baz(); return (if_true * condition) + (if_false * !condition); }
69,934,052
69,934,227
Implementing Matrix operations in C++
I am trying to write a simple C++ header-only library that implements some basic numerical algorithms. It's a hobbyist project, that I wish to do in my personal time. I created a C++ MatrixX class that represents dynamic-size matrices, that is its dimensions can be supplied at run-time. Say, we create a MatrixX object as follows : MatrixXd m { {1, 0, 0}, {0, 1, 0}, {0, 0, 1} }; My MatrixX<scalarType> templated class uses std::vector<scalarType> as the container to store data. Currently, if I write m.row(i), it returns the i'th row vector of the matrix. What I'd also like is, to be able to have m.row(i) on the left-hand side of an assignment statement. Something like: m.row(i) = {{1, 2, 3}}; m.row(j) = m.row(j) - 2*m.row(i); Does anyone have any hints/tips on how to go about this task in C++? I am including my source code, unit tests and documentation as links below, and not pasting it inline for the sake of brevity. Documentation Source code Unit Tests
A common approach for this type of situation is to have the row() method return a proxy object that represents the row without being the row itself. You are then free to implement how this RowProxy behaves by having its operations inspect and maninupulate the matrix it was created from. Here's a rough starting point: template<typename T> class RowProxy { public: template<std::size_t N> RowProxy& operator=(const std::array<T, N>& rhs) { assert(N == row_index_.columns()); // ... } RowProxy& operator=(const RowProxy& rhs) { assert(matrix_.columns() == rhs.matrix_.columns()); // ... } RowProxy& operator=(const Vector<T>& rhs) { assert(matrix_.columns() == rhs.matrix_.columns()); // ... } Vector<T>& operator*(const T& scalar) const { return ...; } // more operators... private: MatrixX<T>& matrix_; std::size_t row_; template<typename T> friend class MatrixX; RowProxy(MatrixX<T>& m, std::size_t r) : matrix_(m), row_(r) {} }; template<typename T> struct MatrixX { public: // ... RowProxy<T> row(std::size_t index) { return RowProxy<T>{*this, index}; } // ... }; template<typename T> Vector<T>& operator*(const T& scalar, const RowProxy* rhs) const { return rhs * scalar; }
69,935,036
69,935,213
include file 'string' not found
Learning C++, day 1, lesson 2 My simple string concatenation test works on the online c++ compiler #include <stdio.h> #include <string> #include <iostream> int main() { // Declare and initialize string std::string mystr = "bananas"; std::cout << "Gwen Stefani is " << mystr << "\n"; return 0; } Which works fine: Gwen Stefani is bananas as expected. However, using Tiny CC I get the error: Error: include file 'string' not found Still new to compilers, all being equal... So I'm a little confused as to what's gone wrong.
Tiny CC is a C compiler, it does not support C++. Since <string> is a C++ standard header, it is not supported by Tiny CC.
69,935,181
69,935,404
Segmentation Fault in C++ With for Loop
I am making an Ant simulation with SDL2 and when I run my code it soon crashed giving me a segmentation fault. I believe this is from trying to access negative values in an array. I tried to make it so the Ant can't do this by giving an if statement checking its value on the "grid" I made out of squares. I added an if statement on line 420 to try and stop my theory but it didn't do anything. Does anyone see the issue here? My Grid Initialiation: struct Wall { bool IsAlive; int Health = 10; SDL_Rect Rect; bool isAnt; bool IsHome; bool IsFood; }; This is where I set up the rects: int count = 0; for (int i = 0; i < 1440; i += 4) { for (int j = 0; j < 795; j += 4) { SDL_Rect Rect = {i, j, 4, 4}; wall[count].Rect = Rect; wall[count].IsAlive = true; if (i < 10) { if (j < 10) { wall[count].IsAlive = false; } } count++; } } And this is where I do the Ant Digging: void Break(int AntID, int SurroundingSqr /*Clockwise*/) { if (SurroundingSqr == -199) { if (A[AntID].PosID > 100) { wall[A[AntID].PosID + SurroundingSqr].Health--; if (wall[A[AntID].PosID + SurroundingSqr].Health == 0) { wall[A[AntID].PosID + SurroundingSqr].IsAlive = false; } } } else { wall[A[AntID].PosID + SurroundingSqr].Health--; if (wall[A[AntID].PosID + SurroundingSqr].Health == 0) { wall[A[AntID].PosID + SurroundingSqr].IsAlive = false; } } } If you want to see all the code you can go to this Gist
You should include all the headers you need. You are missing #include <ctime>. You have undefined behavior because of indices running out of bounds, as can be seen when running your program compiled with -g -fsanitize=address,undefined: ant.cpp:350:34: runtime error: index -199 out of bounds for type 'Wall [572397]' ant.cpp:356:32: runtime error: index -1 out of bounds for type 'Wall [572397]' ================================================================= ==3989611==ERROR: AddressSanitizer: global-buffer-overflow on address 0x00000042fae4 at pc 0x000000405540 bp 0x7ffe896fa2e0 sp 0x7ffe896fa2d8 READ of size 1 at 0x00000042fae4 thread T0 #0 0x40553f in MoveLeft(int) /home/ted/proj/stackoverflow/ant.cpp:356 #1 0x407f87 in MakeAntActions() /home/ted/proj/stackoverflow/ant.cpp:213 #2 0x402687 in main /home/ted/proj/stackoverflow/ant.cpp:102 #3 0x7ff7a0671b74 in __libc_start_main (/lib64/libc.so.6+0x27b74) #4 0x40293d in _start (/home/ted/proj/stackoverflow/ant-g+++0x40293d) I would start nesting out the problem by following the call chain from line 102: MakeAntActions(); ➔ 213: MoveLeft(i); ➔ 350 and 356 (where it croaks) if (wall[A[AntID].PosID - 199].IsAlive) // line 350 index -199 if (wall[A[AntID].PosID - 1].IsAlive) // line 356 index -1 So, A[AntID].PosID is 0 at the time the program reaches these lines which creates these negative indices - and negative indices are not allowed. Compile with -g -fsanitize=address,undefined to get hints like this.
69,935,403
69,935,522
Extracting an username from the database
I'm relatively new to the pqxx library and so I can't seem to figure out how to get data out of the database. I have my header file for the DBUser class #pragma once #include <string> class DBUser { private: std::string m_user, m_password; public: void CreateUser(std::string const& user, std::string const& pw); void LoginUser(std::string const& user, std::string const& pw); }; and this is the cpp with the login implementation #include "DBUser.h" #include "DBLink.h" #include <pqxx/pqxx> void DBUser::CreateUser(std::string const& user, std::string const& pw) { pqxx::work worker(*DBLink::GetInstance()); try { worker.exec0("INSERT INTO users VALUES('" + user + "', " + "'" + worker.conn().encrypt_password(user, pw, "md5") + "')"); worker.commit(); } catch (const std::exception& e) { worker.abort(); throw; } } void DBUser::LoginUser(std::string const& user, std::string const& pw) { pqxx::work worker(*DBLink::GetInstance()); try { pqxx::result username_result = worker.exec0("SELECT username FROM users WHERE username=" + 'user'); worker.commit(); } catch (const std::exception& e) { worker.abort(); throw; } } Whenever I try to run the program I get an error in the xstring file from c++. I also tried getting the data necessary using the row class but to no success, the same error, so can somebody show me and explain how to output data from the database ? Edit: Added the exact error im getting
Okay, you're not going to want to do it that way. You should use positional arguments and prepared statements. Look at this page: https://libpqxx.readthedocs.io/en/6.4/a01480.html For instance, here's some code of mine: static constexpr char const * INSERT_LIST { "author_id, series_id" }; void DB_AuthorSeries_Base::doInsert(pqxx::connection &conn, AuthorSeries &obj) { pqxx::work work {conn}; string sql { string{"INSERT INTO author_series ("} + INSERT_LIST + ") VALUES (nullif($1, 0), nullif($2, 0)) RETURNING id" }; pqxx::result results = work.exec_params(sql, obj.getAuthorId(), obj.getSeriesId()); work.commit(); obj.setId(results[0][0].as<int>()); } Notice the $1, T2, etc. Now, I don't know if your insert statement is going to do what you want, as I always use createuser. BUT... It is a very very VERY bad habit to let your SQL calls have raw data in them. That's how SQL injection attacks where, where people write naughty data into your app in order to hack into your system. Never, never, never do that. Always have your data in prepared statements similar to what I'm showing here.
69,935,772
69,936,298
Weird value and overriding text on variadics
I'm trying to create a logging system where you push a log string into a vector and then print all the logs by looping through the vector, but there seems to be an issue where the strings inside my vector are getting replaced by the most recent string pushed, as well as weird characters being added. struct color { color(unsigned int nr, unsigned int ng, unsigned int nb, unsigned int na) : r(nr), g(ng), b(nb), a(na) {} unsigned int r, g, b, a; }; struct info { const char* text; float time; color col; info(const char* ntext, float ntime, color ncol) : text(ntext), time(ntime), col(ncol) { } }; class event_logger { public: std::vector<info> info_list; void add_log_messasge(color col, const char* message, ...) { char fmsg[512] = { '\0' }; va_list list; va_start(list, message); vsprintf_s(fmsg, 512, message, list); va_end(list); this->info_list.push_back(info(fmsg, 10.0f, col)); // limit to 12 messages at a time if (this->info_list.size() > 12) this->info_list.pop_back(); } void print_log_info() { /* Don't run if the vector is empty. */ if (!info_list.empty()) { for (size_t i = 0; i < info_list.size(); i++) { printf_s("%s\n", info_list[i].text); } } } }; int main() { event_logger log; log.add_log_messasge(color(255, 255, 255, 255), "welcome (%.3f, %s)", 3.14f, "WHAT THE FUCK"); log.add_log_messasge(color(255, 255, 255, 255), "unlucky %s", "dude"); log.print_log_info(); } Does anyone know what the problem is?
your struct struct info { const char* text; float time; color col; info(const char* ntext, float ntime, color ncol) : text(ntext), time(ntime), col(ncol) { } }; is copying an address to a local variable fmsg. The life time of fmsg is circumscribed in the scope of add_log_messasge (you got a typo). Storing the address of a local variable and use it externally of its scope is undefined behavior. use a std::string to store the value of fmsg by copying it and it will work. struct info { std::string text; float time; color col; info(const char* ntext, float ntime, color ncol) : text(ntext), time(ntime), col(ncol) { } }; You need to change your way of printing it by using c_str() void print_log_info() { /* Don't run if the vector is empty. */ if (!info_list.empty()) { for (size_t i = 0; i < info_list.size(); i++) { printf_s("%s\n", info_list[i].text.c_str()); } } } Note: Your check that is using empty isn't really necessary since an empty vector call of size returns 0 which will never start your for loop (i=0 can't be lower of size 0)
69,935,919
69,936,230
C++ - why isn't size/ssize defined for tuple (or wherever tuple_size_v is)?
I'm trying to imagine a scenario where std::size is inappropriate for std::tuple and I'm coming up blank. It supports std::array, but that has its own size() method, so there's no need to specialize. But it also supports T[N], presumably because it's statically sized even if it doesn't have a size() method (it doesn't even have std::tuple_size_v.) So why doesn't std::tuple get std::size support or a size() method? I even thought maybe having std::tuple_size_v means it doesn't need one, but the same goes for std::array.
First, some background to understand what the purpose of std::size even is: Similar to how iterators are generalisations of what pointers are, the standard containers are generalisations of what arrays are (pointers being iterators of arrays). They all contain elements of homogeneous types i.e. all elements have the same type, and they can be iterated over. Unlike pointers which do actually satisfy the abstract iterator concept, arrays were not given the same honour. This may have been because the interface of pointer/iterator could be satisfied by a few simple operators, while containers required several functions to use. Perhaps the committee preferred the object oriented interface of member functions over free functions that are the only possibility for arrays. It can nevertheless be useful to write generic functions and classes that can treat arrays through the same interface. Although an array wrapper template was introduced in C++11 (std::array), which actually is a container (well, almost; it doesn't satisfy a few properties that containers are required to have), it cannot satisfy all use cases where refactoring is not an option (consider for example C interfaces). C++11 and later versions also introduced free functions (templates) that do nothing but forward the call to the corresponding member function of a container, overloaded with a template that does the identical operation on an array. These overloads are such generic interface that can be used with arrays and containers within templates. They are: std::swap C++11 std::{c,}begin C++11 std::{c,}end C++11 std::size C++17 std::empty C++17 std::data C++17 Besides being generic, std::end and std::size in particular also implement functionality that is error prone to beginners. Now for the question: why isn't size/ssize defined for tuple (or wherever tuple_size_v is)? The original proposal is n4017. It contains no rationale for not supporting tuples. I don't know if the committee ever even thought to consider it. But if they did, since such feature isn't in the standard, then they would have rejected (tenatively at minimum) the idea. Tuple isn't a container, and it doesn't have the member function size. It's significantly further from a container than an array is. Crucially, the elements of a tuple are heterogeneous; they consist of objects of differing types. They cannot be iterated over with iterators in the same sense that containers can be. Tuples could however be seen as an even higher generalisation of containers. Perhaps in distant future, Boost.Fusion will be incorporated into the standard and we will have a common interface with containers and tuples. But if we are in that timeline, then we are still in the relative past. It won't happen until/unless it has been proposed and accepted into the standard. Curiously, std::tuple_size is a common interface between std::tuple and std::array (but not bare array).
69,936,383
69,936,434
How to design a class with const, non const member function and it can take over const raw pointer?
I have a class, it can define some operations on a raw pointer. For example, the class is called Vector. class Vector { public: explicit Vector(double *ptr_, int size_) :ptr(ptr_), size(size_) { } // some operation change data in ptr void notConstOperation() { ptr[0]=ptr[0]+1; } // some operation do not change data in ptr double constOperation() const { return ptr[0]; } private: double *ptr; int size; }; And I have a lot of others operations on Vector int doNotConstOperation(Vector &vec); int doConstOperation(const Vector &vec); My problem is, I find I can not create the Vector object from a raw const pointer. Vector createVectorFromNonConstPtr(const *ptr, int size) { // ok. return Vector(ptr, size); } Vector createVectorFromConstPtr(const double *ptr, int size) { // can not create, because the args in Vector is not const. return Vector(ptr, size); } I want to use the Vector in the follow way: // using const ptr const double *cptr; const Vector cvec = createVectorFromConstPtr(cptr, 10); cvec.constOperation(); doConstOperation(cvec); // using non-const ptr const double *ptr; Vector vec = createVectorFromPtr(cptr, 10); vec.notConstOperation(); doNotConstOperation(vec); I know splitting the class into Vector and ConstVector can help. But it leads to some verbose, the const operation will be written twice. How can I implement that? Any suggestion is I looking forward. Thanks for your time.
Any suggestion is I looking forward Inheritance. class ConstVector { const double *ptr; protected: double *_ptr() { return const_cast<double *>(ptr); } void _set_ptr(double *new_ptr) { ptr = new_ptr; } friend Vector; }; class Vector : ConstVector { // some operation change data in ptr using ConstVector::ConstVector; void notConstOperation() { // _ptr() is inherited. _ptr()[0] = _ptr()[0]+1; } } Template overload. template<bool isconst> class Vector { double *ptr; Vector(double *ptr) : ptr(ptr) {} template<int empty = 1> Vector(const double *ptr, typename std::enable_if<isconst && empty>::type* = 0 ) : ptr(const_cast<double *>(ptr)) {} typename std::enable_if<!isconst>::type notConstOperation() { ptr[0] = ptr[0] + 1; } }; Runtime tracking. class Vector { bool isconst; double *ptr; Vector(double *ptr) : ptr(ptr), isconst(0) {} Vector(const double *ptr) : ptr(const_cast<double *>(ptr)), isconst(1) {} void notConstOperation() { assert(!isconst); .... } }; Or return a const vector and const cast to construct it: class Vector { public: Vector(double *ptr, int size) : ptr(ptr), size(size) {} void notConstOperation() { .... } double constOperation() const { ... } private: double *ptr; int size; }; Vector createVectorFromNonConstPtr(double *ptr, int size) { return Vector(ptr, size); } const Vector createVectorFromConstPtr(const double *ptr, int size) { return Vector(const_cast<double*>(ptr), size); }
69,936,613
69,936,657
Cuda number of elements is larger than assigned threads
I am new to CUDA programming. I am curious that what happens if the number of elements is larger than the number of threads? In this simple vector_add example __global__ void add(int n, float *x, float *y) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) y[i] = x[i] + y[i]; } Say the number of array elements is 10,000,000. And we call this function using 64 blocks and 256 threads per block: int n = 1e8; int grid_size = 64; int block_sie = 256; Then, only 64*256 = 16384 threads are assigned, what would happen to the rest of the array elements?
what would happen to the rest of the array elements? Nothing at all. They wouldn't be touched and would remain unchanged. Of course, your x array elements don't change anyway. So we are referring to y here. The values of y[0..16383] would reflect the result of the vector add. The values of y[16384..9999999] would be unchanged. For this reason (to conveniently handle arbitrary data set sizes independent of the chosen grid size), people sometimes suggest a grid-stride-loop kernel design.
69,937,130
69,937,958
How can I make sure a type only appear once in a template parameter?
Let's say I have an alias: using bar = foo<string, string, int>; How can I make sure that "string" only appear once in the parameter? If it appears more than once then throw an error. I have made a function to count how many times a type appeared in the parameter but failed to implement the idea. template <class T> constexpr std::size_t type_count_impl(std::size_t count = 0) { return count; }; template <class T, class T1, class... Types> constexpr std::size_t type_count_impl(std::size_t count = 0) { return type_count_impl<T, Types...>(count + (std::is_same<T, T1>::value ? 1 : 0)); }; template <class T, class... Types> constexpr std::size_t type_count() { return type_count_impl<T, Types...>(); };
For a simple compile time error if any type in the variadic parameter pack is duplicated, it's pretty simple: template <typename T> struct Base{}; template <typename... Ts> struct NoDuplicates : Base<Ts>... { constexpr operator bool() const { return true; } }; That's it, and if it's what you need it will compile faster than any recursive template metaprogramming, fold expression, or type-trait approach. In fact, I know of no faster technique at compile time. This works because a class is not allowed to inherit from the same base class twice. The reason it inherits from Base<T> instead of just T, is in case T is a type you can't inherit from, such as a primitive integral value, or an array, or void, etc. To use: template <typename... Ts> class Foo { static_assert(NoDuplicates<Ts...>{}); }; Foo<int, char, int> foo; // ERROR (see below) <source>:3:34: error: duplicate base type 'Base<int>' invalid 3 | template <typename... Ts> struct NoDuplicates : Base<Ts>... { Now, if you don't want a compile error, but want to compute a boolean indicating if there are any duplicates, it's a little more complicated, but not too bad. Comments show the 3 cases to check: template <typename T, typename... Rest> constexpr bool hasDuplicates() { // Check T against each item in Rest, and if any match we have duplicates if ((std::is_same_v<T, Rest> || ...)) return true; // Is there anything left to check in Rest? If not, no duplicates. if constexpr (sizeof...(Rest) == 0) return false; // T isn't duplicated, but is anything in Rest duplicated? return hasDuplicates<Rest...>(); } It can be used similarly: template <typename... Ts> class Foo { static_assert(not hasDuplicates<Ts...>()); }; Foo<int, std::string, std::string> foo; // Error, there are dupes And finally, if you only care if a specific type is duplicated, it is even easier: // Check if Needle is found 2 or more times in this Haystack template <typename Needle, typename... Haystack> constexpr bool hasDuplicateInList() { return ((std::is_same_v<Needle, Haystack> + ...)) > 1; } As far as "throwing" goes, if that's what you want, you can always throw an exception if you detect the boolean having a disallowed value in a normal if
69,937,136
69,943,669
Binary Tree with parent pointer in node keeps crashing on Deletion with error 0xDDDDDDDD
I was experimenting a little bit with C++ and decided to try and create whole tree deletion method for Binary Tree. For some reason I keep getting pointer error because pointer is 0xDDDDDDDD. If someone can explain me why it does not work I would appreciate it so I can learn more about pointers. struct Node { Node* parent; Node *left, *right; int value; inline Node() : parent(nullptr), left(nullptr), right(nullptr), value(0){} ~Node() = default; }; class BST { public: Node* root; public: BST() = default; inline BST(int i) { root = new Node(); root->value = i; root->parent = nullptr; root->left = nullptr; root->right = nullptr; } BST(const BST& bst) = default; void Insert(int i); void DeleteAll(Node* node); }; #include <iostream> int main() { BST t(20); t.root->left = new Node(); t.root->left->value = 22; t.root->left->parent = t.root; t.root->right = new Node(); t.root->right->value = 15; t.root->right->parent = t.root; t.DeleteAll(t.root); } void BST::Insert(int i) { } void BST::DeleteAll(Node* node) { Node* target = node; std::cout << "Probing node with value " << node->value << std::endl; if (node->left == nullptr && node->right == nullptr) { target = node->parent; std::cout << "Node deleted with value: " << node->value << std::endl; delete node; if (target == nullptr) { std::cout << "Found and deleted root!" << std::endl; return; } std::cout << "Parents node value: " << target->value << std::endl; } else if (node->left != nullptr) { std::cout << "Found left ptr with value: " << node->left->value << std::endl; target = node->left; } else if(node->right != nullptr) { std::cout << "Found right ptr with value: " << node->right->value << std::endl; target = node->right; } DeleteAll(target); } The prompt from the console I am getting is: Probing node with value 20 Found left ptr with value: 22 Probing node with value 22 Node deleted with value: 22 Parents node value: 20 Probing node with value 20 Found left ptr with value: -572662307 Probing node with value -572662307 In DeleteAll() function when it gets back to parent node to search if there is any children that is not null it always finds the left child which I deleted before. Shouldn't it be null? And there it crashes. I have no idea why is it doing that but something is probably in the delete function. This is not a homework of any kind I am just trying to learn why this does not work.
When I run your code I get this output, and it throws "read access violation": Found left ptr with value: -572662307 -572662307 is same as 0xDDDDDDDD This is specific for Visual Studio in debug mode. Sometimes you may not get this value. The problem is you never allocated memory for parent (which you don't even need, more on that later) then you try to delete it over and over. You should rewrite you code like this to understand it better: void DeleteAll(Node* node) { printf("node: %p\n", node); Node* target = node; if (!node->left && !node->right) { target = node->parent; //this was never allocated, supposed to be NULL delete node; if (target == nullptr) //target is now undefined, not NULL, can't be tested return; //we may not get here } else if (node->left != nullptr) target = node->left; else if (node->right != nullptr) target = node->right; DeleteAll(target); //could be deleting the same thing again } The output is something like this, with different numbers: node: 012C5078 node: 012D2F00 node: 012C5078 node: 012D2F00 node: DDDDDDDD You see the same values repeated, it's trying to delete twice. The correct DeleteAll function is just this: void BST::DeleteAll(Node* node) { if (!node) return; DeleteAll(node->left); DeleteAll(node->right); delete node; } You will also need a different Delete(Node* node, int value) function which deletes based on value,left,right, this will be used once you properly insert items, and you want to remove some values before BST is destroyed. Try this example instead: https://gist.github.com/harish-r/a7df7ce576dda35c9660
69,937,151
69,947,939
Calling a custom function on each node during DFS traversal
I am wondering what would be the most elegant way to code a DFS traversal that can be adapted to solve different problems (in C++). I was thinking to pass a function pointer and a void * to my function and let the user pass a callback that would be used on every node. This is what I have: traversals.hpp typedef std::shared_ptr<struct Node> NodePtr; typedef std::vector<NodePtr> NodeVector; struct Node { int id{0}; NodeVector children; }; bool NodeIsInVector(NodePtr node, NodeVector node_vector); void DFS(NodePtr node, void (*callback)(NodePtr, void * userdata)=nullptr, void * userdata=nullptr); traversals.cpp bool NodeIsInVector(NodePtr node, NodeVector node_vector){ auto result = std::find(node_vector.begin(), node_vector.end(), node); return result != node_vector.end(); } void DFS(NodePtr node, void (*callback)(NodePtr, void * userdata), void * userdata){ static NodeVector visited; if (!NodeIsInVector(node, visited)) { visited.push_back(node); if (callback){ callback(node, userdata); } } for (auto&& n : node->children){ if (!NodeIsInVector(n, visited)){ DFS(n, callback, userdata); } } } Driver code Here the callback just counts the nodes and increments and integer. Assume that root is a Node pointer and that a tree was defined. The tree has 7 nodes, so the value of count is expected to be 7 after the traversal. int count = 0; DFS(root, [](NodePtr node, void * count){ ++*(int*)count; }, (void*) &count); std::cout << "DFS count: there are " << count << " nodes.\n"; But the output is: DFS count: there are 0 nodes. The callback gets called (verified by outputting to stdout). The problem is that the userdata variable does not get updated. My questions are: Is this a valid approach to achieve what I want? Are there better approaches? What would be the error I made?
Correct me if I am wrong but I suspect the problem was due to the static variable defined inside DFS. I omitted to mention in my question that DFS was called with a different callback that did not increment the count variable before being called with the callback that did. I though it was not relevant to my question. Could having a static variable declared in the function cause the callback function not to be replaced during the second call? The following version works as expected. I also replaced the function pointer with an std::function reflecting some suggestions made in comments but more importantly I created a wrapper that declares the visited NodeVector and this allowed me to not have any static declarations. void DFS(NodePtr &node, std::function<void(NodePtr)> callback){ NodeVector visited; _DFS(node, callback, visited); } void _DFS(NodePtr &node, std::function<void(NodePtr)> callback, NodeVector& visited){ if (!NodeIsInVector(node, visited)) { visited.push_back(node); callback(node); } else { for(auto item : visited){ std::cout<<item->id << " "; } std::cout << "\n"; } for (auto&& n : node->children){ if (!NodeIsInVector(n, visited)){ _DFS(n, callback, visited); } } } And the driver code: int count = 0; DFS(root, [&count](NodePtr node) mutable { ++count; }); std::cout << "DFS count: there are " << count << " nodes.\n"; Produces: DFS count: there are 7 nodes Note that the same function but with a static NodeVector visited; instead of the wrapper strategy does not work as intended. I am still not 100% clear why.
69,937,425
69,937,650
How to calculate a rorate ellipse point's tangent?
I got a rotate ellipse by using fitEllipse, and i want calculate the tangent of the points on this ellipse, i tried this: static Line getTangent(const RotatedRect & ell, const Point & p) { // double rad = ell.angle*CV_PI/180; // double a = ell.size.width/2; // double b = ell.size.height/2; // if(fabs(rad-CV_PI/2)<CV_PI/4) // { // rad -= CV_PI/2; // b = ell.size.width/2; // a = ell.size.height/2; // } double rad = (ell.angle-90)*CV_PI/180; double a = ell.size.height/2; double b = ell.size.width/2; double cr = cos(rad); double sr = sin(rad); double s = ell.center.x; double t = ell.center.y; double k = - b*b / (a*a) * ((p.x-s)*cr+(p.y-t)*sr) / (-(p.x-s)*sr+(p.y-t)*cr); return Line(k,p); // The line through p with grad k } the ellipse {center:(523.965, 525.291), size:{444.735 x 662.827}, angle:81.7087} with point p(313, 713) result is right, but ellipse {center:(638.93, 639.36), size:{572.964 x 787.908}, angle:6.27164} with point p(756, 985) result is wrong, i guess it is the angle calculation problem, but i dont know how to solve it. Can someone help me ?
A picture is worth a thousand words: You need to check whether point lies outside of ellipse (with opencv function if exists or with ellipse equation)
69,937,956
69,938,053
Why do 1ll << i does give us correct answer but not long long i ; 1<<i?
Since 1 operand in << operator is of long long type, and the answer should be stored as long long, I am a little surprised by this behavior can anyone explain why this happens? For Example: #include<bits/stdc++.h> using namespace std; int main(){ long long p=33; long long a = 1<<p; cout<<a; } //This gives the wrong output int main(){ long long a = 1ll<<33; cout<<a; } //this gives right output
C++11 (N3690) 5.8 Shift operators [expr.shift] p1: The operands shall be of integral or unscoped enumeration type and integral promotions are performed. The type of the result is that of the promoted left operand. So the type of 1 << i is int, whereas 1LL << i has type long long, which can usually represent a greater range of values. The shift operators are exceptional here; most other operators follow the usual arithmetic conversions [5 p10], which cause both operands to be converted to the same type, roughly speaking the larger of the two.
69,937,999
69,938,029
Running an object call within an object call
I have a struct struct Stuff { float something (int& prereq) { float s = prereq+2; return s; } double something_else(int& prereq_ref, float& thing_ref, float& s_ref ){ s2 = s + thing + h; return s2; } }; Then I run a call in my main loop float thing = 4; int prereq = 2; int main() { Stuff item; double n = item.something_else(prereq, thing, item.something(prereq)); return 0; } The call in main doesn't run, however the following line does float s = item.something(prereq); double n = item.something_else(prereq, thing, s); Am I missing something obvious? I'd rather not waste memory on what seems to be an unnecessary float.
float& is an lvalue reference type. It can only take values that can be assigned to, such as variables. float s = item.something(prereq); double n = item.something_else(prereq, thing, s); Here, s is a variable. It has a place in memory and the expression s = ... would be meaningful. On the other hand, double n = item.something_else(prereq, thing, item.something(prereq)); Here, the value is item.something(prereq), which is not an lvalue. We can't write item.something(prereq) = ...; it doesn't make sense to assign to the return value of that function. If you're not planning to modify the function arguments, take them by constant reference or by value. double something_else(const int& prereq_ref, const float& thing_ref, const float& s_ref) or double something_else(int prereq_ref, float thing_ref, float s_ref) for large data like structures or classes, you might consider using const&, but for integers and floats, it's unnecessary overhead and by-value parameters will do fine.
69,938,045
69,938,725
How to convert this JavaScript code to C++
Problem is to return any one combination from given array that sums up to the target. I'm new to C++. How can I complete the function howSum() below? I can't return null here since the return type is vector. Also I'm having trouble passing the vectors. JavaScript: const howSum = (targetSum, numbers) => { if (targetSum === 0) return []; if (targetSum < 0) return null; for (let num of numbers) { const remainder = targetSum - num; const remainderResult = howSum(remainder, numbers); if (remainderResult !== null) { return [...remainderResult, num]; } } return null; }; C++: vector<int> howSum(int targetSum, vector<int> numbers) { if(targetSum == 0) return {}; if(targetSum < 0) return; //can't return null here in C++ for (int i = 0; i < numbers.size(); i++) { int remainder = targetSum - numbers[i]; vector<int> remainderResult = howSum(remainder, numbers); if(pass) { pass } } }
You can use C++17 std::optional and return std::nullopt when it does not contain value. #include <optional> #include <vector> std::optional<std::vector<int>> howSum(int targetSum, const std::vector<int>& numbers) { if (targetSum == 0) return std::vector<int>{}; if (targetSum < 0) return std::nullopt; for (auto numer : numbers) { const auto remainder = targetSum - numer; auto remainderResult = howSum(remainder, numbers); if (remainderResult) { remainderResult->push_back(targetSum); return remainderResult; } } return std::nullopt; }
69,939,017
69,939,092
What is the best way to get user appdata folder location on windows?
I'm writing an application for windows, and I need to find the location of the appdata folder, to save, well, appdata to it. I'm using C++. When I did some research on this, I found some answers like, for example "getenv("APPDATA")". I could use that but that question was answered in like 2012 so there might be better ways to do it now in 2021. Thanks for the help! #include <iostream> int main() { std::string appdataLocation; //TODO: Find appdata folder location. //enter code here std::cout << appdataLocation << '\n'; } Some people have been suggesting that this is a duplicate question. That question was asked 10 years ago. There may be better ways to do it right now, which is why I'm asking.
you can use Windows API alternatively: TCHAR appdata[MAX_PATH] = {0}; SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, appdata); https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetfolderpatha
69,939,946
69,945,233
How to determine if an argment was provided to boost::program_options, or if the default is used instead?
Using boost::program_options, I need to set the default_value for having that default visible in the help message. However, it is still needed to know if the default was applied or if an argument was provided. (The logic will, in certain cases override an existing configuration if the argument pas provided). Possible solutions: Remove default values: but then the help message will not show the default. Find a way to check if an argument was provided (How?) Create the option_description twice (one with defaults, another without). Not ideal. int main( int argc, char* argv[]) { namespace po = boost::program_options; namespace fs = boost::filesystem; std::string ip; std::string port; const std::string ip_arg = "ip"; const std::string port_arg = "ip"; po::options_description options("Options"); options.add_options() (ip_arg, po::value<std::string>(&ip, "IP")->default_value("127.0.0.1") (port_arg, po::value<std::string>(&port, "Port")->default_value("80")) ; po::variables_map vm; try { using bs = po::command_line_style::style_t; boost::program_options::store( boost::program_options::command_line_parser(argc, argv) .options(options) .style(bs::long_allow_next | bs::allow_long | bs::allow_short | bs::allow_dash_for_short | bs::long_allow_adjacent | bs::short_allow_adjacent | bs::short_allow_next | bs::allow_long_disguise) .run(), vm); po::notify(vm); } catch( ...) { std::cerr << "Some error" << std::endl; return 1; } std::stringstream ss; ss << options; std::cout << ss.str() << std::endl; // Print help, visible defaults if (vm.count(port_arg)) { // Argument was provided, so make something } else { // Argument was no provided, make something else. } return 0; } How can I detect if an argument was provided, or if the default was applied?
Your options descriptions are broken. Let's fix them. I opted against the ip_arg/port_arg variables (note how you had them copy pasted wrong anyways). po::options_description options("Options"); options.add_options() ("ip", po::value<std::string>(&ip)->default_value("127.0.0.1"), "IP") // ("port", po::value<std::string>(&port)->default_value("80"), "Port") ; Now you can be sure that port is always set, so .count() or .contains() are redundant. Instead, ask the map entry whether it has been defaulted: if (vm["port"].defaulted()) { std::cout << "Port defaulted (" << port << ")\n"; } else { std::cout << "Port specified as " << port << "\n"; } Live Demo Live On Coliru #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <iostream> namespace po = boost::program_options; namespace fs = boost::filesystem; int main( int argc, char* argv[]) { std::string ip; std::string port; po::options_description options("Options"); options.add_options() ("ip", po::value<std::string>(&ip)->default_value("127.0.0.1"), "IP") // ("port", po::value<std::string>(&port)->default_value("80"), "Port") ; po::variables_map vm; try { using bs = po::command_line_style::style_t; boost::program_options::store( boost::program_options::command_line_parser(argc, argv) .options(options) .style(bs::long_allow_next | bs::allow_long | bs::allow_short | bs::allow_dash_for_short | bs::long_allow_adjacent | bs::short_allow_adjacent | bs::short_allow_next | bs::allow_long_disguise) .run(), vm); po::notify(vm); } catch (...) { std::cerr << "Some error" << std::endl; return 1; } std::cout << options << std::endl; if (vm["port"].defaulted()) { std::cout << "Port defaulted (" << port << ")\n"; } else { std::cout << "Port specified as " << port << "\n"; } } Prints e.g. $ ./test --ip=192.168.1.2 Options: --ip arg (=127.0.0.1) IP --port arg (=80) Port Port defaulted (80) or $ ./test --port=8080 Options: --ip arg (=127.0.0.1) IP --port arg (=80) Port Port specified as 8080
69,940,027
69,940,735
Why is converting constructor of std::packaged_task explicit?
Why is the converting constructor of std::packaged_task explicit, while the same constructor of std::function is not? I cannot find any reasoning for it. This, for example, forces casting when passing a lambda as an argument for a function that has a packaged_task (or a reference to it) as a parameter: void f1(std::function<void()>); std::future<void> f2(std::packaged_task<void()>); int main() { f1( []{ } ); // ok auto fut = f2( []{ } ); // error auto fut = f2( (std::packaged_task<void()>) []{ } ); // ok fut.wait(); }
Consider following example. Lets create a template class that emulates class with non-explicit templated converting constructor. #include <iostream> // Hypothetical overloaded constructor template <class T> struct Foo { template <class F> Foo(F&& f ) { std::cout << "Initialization of Foo \n"; } Foo(const Foo& ) { std::cout << "Copy of Foo\n"; } Foo(Foo&& ) { std::cout << "Move of Foo\n"; } }; void bar( Foo<int> f ) {} int main() { int a = 0; std::cout << "1st case\n"; bar(a); std::cout << "2nd case\n"; bar(Foo<int>(a)); // incorrect behaviour } The output will be 1st case Initialization of Foo 2nd case Initialization of Foo The template hijacks control in both cases! You actually cannot use copy\move constructors in such situation. A simplest way to avoid it is to make conversion explicit. #include <iostream> // Analog of standard's constructor idiom template <class T> struct Foo2 { template <class F> explicit Foo2(F&& f ) { std::cout << "Initialization of Foo2 \n"; } Foo2(const Foo2& ) { std::cout << "Copy of Foo2\n"; } Foo2(Foo2&& ) { std::cout << "Move of Foo2\n"; } }; void bar2( Foo2<int> f ) {} int main() { int a = 0; Foo2<int> f{a}; std::cout << "\nProper case 1\n"; // bar2(a); - can't do that bar2(Foo2<int>(a)); std::cout << "Proper case 2\n"; bar2(f); return 0; } Output: Initialization of Foo2 Proper case 1 Initialization of Foo2 Proper case 2 Copy of Foo2 std::function is copyable while std::packaged_task have to define custom move constructor and delete copying constructor. On an attempt to pass std::function , in both cases nothing BAD would happen, the copy and move constructors are likely operate upon function pointer or reference to callable object, std::function is designed to act upon any compatible callable, that includes itself. if you attempt to do that to do that to std::packaged_task, the converting constructor may do something wrong or likely wouldn't compile because it wouldn't be able to work with instance of own class. A statement that looks like copy (but actually is .. a move? assignment?) would be possible.
69,940,116
69,940,196
error: std::string was not declared in this scope, in for loop C++
I was trying to implement code making use of the GMP library for a class, and haven't been able to figure out the source of this issue. I've run similar code before on an unordered_map so this error is confusing me. From what I can tell the std::string should be declared in the scope by the call to the for loop. Could it be related to using the GMP library? int main(int argc, char** argv){ std::map<mpz_class, std::string> number_names; std::ifstream names_file("/srv/datasets/number_names.txt"); if(!names_file.is_open()){ std::cout << "error reading /srv/datasets/number_names.txt\n"; return -1; } mpz_class num; for (std::string name : names_file >> name >> num){ // line throwing error number_names[num] = name; } auto value = mpz_class(argv[1]); std::vector<std::string> output = some_func(value, number_names); } the full error message reads: as10.cpp:75:43: error: ‘name’ was not declared in this scope 75 | for (std::string name : names_file >> name >> num)
for (std::string name : names_file >> name >> num){ number_names[num] = name; } This is not how range-based for loop works in C++, so this is a syntax error. By the looks of it, you have a typo. Maybe what you want is: std::string name; while(names_file >> name >> num){ number_names[num] = name; } Or: for (std::string name; names_file >> name >> num;){ number_names[num] = name; }
69,940,204
69,940,262
Overriding non-virtual function from abstract grandparent class
I am learning and playing around with inheritance and abstract classes. I've run into a predicament that I would appreciate some clarifications on. I am trying to override a non-virtual function from an abstract grandparent class. I am getting an error saying that 'member function declared with 'override' does not override a base class member. I can call the original non-virtual function from child class instances in main(), but not override them in child classes? Here's the code. UPDATE: Error went away when I marked the function as virtual, I would still appreciate an explanation as to why that virtual is necessary? #include <iostream> using namespace std; class A { public: virtual string GetClassName() = 0; void foo(); // <--- this is the problem function { cout << "foo" << endl; } }; class B : public A { public: string GetClassName() override { return "B"; } }; class C1 : public B { public: string GetClassName() override { return "C"; } }; class C2 : public B { public: void foo() override // ERROR:member function declared with override does not override a base class member. { cout << "foo c1" << endl; } }; // testing interface void printName(A* ptr) { cout << ptr->GetClassName() << endl; } int main() { B* b = new B(); C1* c1 = new C1(); C2* c2 = new C2(); printName(b); // prints B printName(c1); // prints C printName(c2); // prints B b->foo(); // prints foo, inherited directly from abstract class c1->foo(); // prints foo, inherited directly from abstract class c2->foo(); // ?? }
You cannot override a non-virtual function. It is as simple as that. Methods in child classes can hide methods of parent classes when they have the same name, for example: struct A { void foo(){} }; struct B : A { void foo() {} }; But thats not overriding. To override the method must be virtual. Thats one of the conditions that the override specifier helps to check: struct A { virtual void foo(){} }; struct B : A { void foo() override {} // <- error if A::foo is not virtual }; PS: I have seen poor tutorials, that use the first example and call that overriding. Thats just wrong.
69,940,329
69,940,397
STL algorithm function with reverse iterators doesn't work
I need to find minimum element in my array, but if amount of minimum elements more than 1, I need to use the most right one. Consider this code: #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int n; cin >> n; vector<int> a(n); for (int& x : a) cin >> x; vector<int>::iterator it_min = min_element(a.rbegin(), a.rend()); } It doesn't work. And it doesn't make sense to me why. Reverse_iterator basically provides all operators needed for correct execution of function. But apparently min_element() expecting only "normal" iterator is being given. Can I somehow bypass that? Ok, I can convert my reverse_iterator to iterator with .base() function member (min_element(a.rbegin().base(), a.rend().base())), but that doesn't resolve my problem since operator+ is now going forward, not backwards. I could not think of anything sensible. Is there an elegant solution to this problem? P.S. There's a solution to my problem with custom comparator and it works with normal iterators, but still I want to find out if there is a solution with reverse_iterators: vector<int>::iterator it_min = min_element(a.begin(), a.end(), [](int min, int b) { return min >= b; }); UPD: After the answer, I understood that everything I said about min_element() is wrong. It can accept reverse_iterators and work with them correctly, but I was confused about why it requires conversion reverse_iterators to iterators, but it didn't required the a.rbegin() and a.rend() to convert to "normal" iterators. It required to convert the returning iterator itself.
You're passing reverse_iterator to min_element, then it returns reverse_iterator too. Change the code to vector<int>::reverse_iterator it_min = min_element(a.rbegin(), a.rend()); Or auto it_min = min_element(a.rbegin(), a.rend()); You can get the vector<int>::iterator from the returned reverse_iterator later by it_min.base() - 1.
69,940,527
69,945,180
Random Occupancy values returned by the "cudaOccupancyMaxActiveBlocksPerMultiprocessor"
I am trying to understand the usage and benefit of the “cudaOccupancyMaxActiveBlocksPerMultiprocessor” method. I am using a slightly modified version of the sample program present on NVIDIA developer forum. Basically, I am asking the user to provide the size of the array. My GPU: NVIDIA GeForce GTX 1070 QUESTIONS: The occupancy values returned by the program are very random. Many times, the program returns different occupancy values for the same input array size, is there anything wrong in the program? As shown in the screenshot, if user passed the array size=512 then, the occupancy value is “13” whereas if I set N=512 directly in the program then the occupancy value is “47”. Why? Why does user provided array size=1024 has occupancy value =0? SAMPLE CODE: Source.cpp #include "kernel_header.cuh" #include <algorithm> #include <iostream> using namespace std; int main(int argc, char* argv[]) { int N; int userSize = 0; //ask size to user cout << "\n\nType the size of 1D Array: " << endl; cin >> userSize; N = userSize>0? userSize : 1024; //<<<<<<<<<<<<<<<-------PROBLEM int* array = (int*)calloc(N, sizeof(int)); for (int i = 0; i < N; i++) { array[i] = i + 1; //cout << "i = " << i << " is " << array[i]<<endl; } launchMyKernel(array, N); free(array); return 0; } kernel_header.cuh #ifndef KERNELHEADER #define KERNELHEADER void launchMyKernel(int* array, int arrayCount); #endif kernel.cu #include "stdio.h" #include "cuda_runtime.h" __global__ void MyKernel(int* array, int arrayCount) { int idx = threadIdx.x + blockIdx.x * blockDim.x; if (idx < arrayCount) { array[idx] *= array[idx]; } } void launchMyKernel(int* array, int arrayCount) { int blockSize; // The launch configurator returned block size int minGridSize; // The minimum grid size needed to achieve the // maximum occupancy for a full device launch int gridSize; // The actual grid size needed, based on input size cudaOccupancyMaxPotentialBlockSize(&minGridSize, &blockSize,MyKernel, 0, 0); // Round up according to array size gridSize = (arrayCount + blockSize - 1) / blockSize; MyKernel << < gridSize, blockSize >> > (array, arrayCount); cudaDeviceSynchronize(); // calculate theoretical occupancy int maxActiveBlocks; cudaOccupancyMaxActiveBlocksPerMultiprocessor(&maxActiveBlocks, MyKernel, blockSize, 0); int device; cudaDeviceProp props; cudaGetDevice(&device); cudaGetDeviceProperties(&props, device); float occupancy = (maxActiveBlocks * blockSize / props.warpSize) / (float)(props.maxThreadsPerMultiProcessor / props.warpSize); printf("\n\nMax. Active blocks found: %d\nOur Kernel block size decided: %d\nWarp Size: %d\nNumber of threads per SM: %d\n\n\n\n", maxActiveBlocks , blockSize, props.warpSize, props.maxThreadsPerMultiProcessor); printf("Launched blocks of size %d. Theoretical occupancy: %f\n", blockSize, occupancy); }
Before asking others for help with a CUDA code that is not working the way you expect, I strongly encourage you to: Use proper CUDA error checking run your code with a sanitizer, such as cuda-memcheck or compute-sanitizer Even if you don't understand the results, the information reported will be useful for those trying to help you. In your case, you are doing something illegal with your kernel. Specifically, you have passed it host pointers (the one returned by calloc is a host pointer). You pretty much can't use such a pointer in CUDA (i.e. for CUDA device code), and this is a basic CUDA programming principle. To understand one method to structure such a code, so that your kernel can actually do something useful, please refer to the vectorAdd CUDA sample code. When your kernel attempts to use this host pointer, it makes illegal accesses. At least in my case, when I enter 2048 for the data size, and implement proper CUDA error checking, I observe that the kernel and all subsequent CUDA activity returns an error code, including your call to cudaOccupancyMaxActiveBlocksPerMultiprocessor. That means, that that call is not doing what you expect, and the data it returns is garbage. So that is at least one reason why you are getting garbage calculation values. When I fix that issue (e.g. by replacing the calloc with a suitably designed call to cudaMallocManaged), then your code for me reports an occupancy calculation of 1.0, for input data sizes of 512, 1024, and 2048. So there is no variability that I can see, and at best, if you still have questions, I think you would need to restate them (in a new question). I'm not suggesting that if you fix this, everything will be fine. But this problem is obscuring any ability to make useful analysis.
69,940,833
69,941,266
Implicit type conversion for operator==
I'd like to have a way to compare different data types that are internally represented by an array (e.g. a string and a vector of chars) using a common array reference type. Consider the following code: template <typename T> struct ArrayConstRef { const T *data; size_t length; }; template <typename T> bool operator==(ArrayConstRef<T> a, ArrayConstRef<T> b); template <typename T> class ContainerA { public: operator ArrayConstRef<T>() const; explicit operator const T *() const; }; template <typename T> class ContainerB { public: operator ArrayConstRef<T>() const; explicit operator const T *() const; }; int main() { if (ContainerA<int>() == ContainerB<int>()) // error - no matching operator== printf("equals\n"); return 0; } The overloaded operator== isn't matched even though the implicit conversion is available. Interestingly, if I removed the explicit keywords, the compiler manages to convert both objects to pointers and do the comparison that way (which I don't want). Why does one implicit conversion work but not the other? Is there a way to make it work?
This can be solved using SFINAE and little changes in code of your classes. #include <cstddef> #include <cstdio> #include <type_traits> template <typename T> struct ArrayConstRef { const T *data; size_t length; }; // This is needed to override other template below // using argument depended lookup template <typename T> bool operator==(ArrayConstRef<T> a, ArrayConstRef<T> b){ /* Provide your implementation */ return true; } template < typename Left, typename Right, // Sfinae trick :^) typename = std::enable_if_t< std::is_constructible_v<ArrayConstRef<typename Left::ItemType>, const Left&> && std::is_constructible_v<ArrayConstRef<typename Right::ItemType>, const Right&> && std::is_same_v<typename Left::ItemType, typename Right::ItemType> > > inline bool operator==(const Left& a, const Right& b){ using T = typename Left::ItemType; return ArrayConstRef<T>(a) == ArrayConstRef<T>(b); } template <typename T> class ContainerA { public: // Add type of element using ItemType = T; operator ArrayConstRef<T>() const; explicit operator const T *() const; }; template <typename T> class ContainerB { public: // Add type of element using ItemType = T; operator ArrayConstRef<T>() const; explicit operator const T *() const; }; int main() { if (ContainerA<int>() == ContainerB<int>()) // no error :) printf("equals\n"); return 0; } Compiles well with GCC 11.2 -std=c++17. If you can use C++20, it is better to use concepts for this. Code below compiles with GCC 11.2 -std=c++20. #include <cstddef> #include <cstdio> #include <type_traits> template <typename T> struct ArrayConstRef { const T *data; size_t length; }; // This is needed to override other template below // using argument depended lookup template <typename T> bool operator==(ArrayConstRef<T> a, ArrayConstRef<T> b){ /* Provide your implementation */ return true; } template <typename Container> concept ConvertibleToArrayConstRef = requires (const Container& a) { ArrayConstRef<typename Container::ItemType>(a); }; template < ConvertibleToArrayConstRef Left, ConvertibleToArrayConstRef Right > requires (std::is_same_v< typename Left::ItemType, typename Right::ItemType> ) inline bool operator==(const Left& a, const Right& b){ using T = typename Left::ItemType; return ArrayConstRef<T>(a) == ArrayConstRef<T>(b); } template <typename T> class ContainerA { public: // Add type of element using ItemType = T; operator ArrayConstRef<T>() const; explicit operator const T *() const; }; template <typename T> class ContainerB { public: // Add type of element using ItemType = T; operator ArrayConstRef<T>() const; explicit operator const T *() const; }; int main() { if (ContainerA<int>() == ContainerB<int>()) // no error :) printf("equals\n"); return 0; }
69,941,533
69,941,748
C++ Recursive Function
I am student who just learned c++ not long ago. I have a doubt in mind, for the linked list code below, I don't quite understand the logics behind it, why does the function when it reaches return, it will continue to execute the func1() and cout command ? Isn't it whenever a the programs reaches return it will automatically exits the function and ignore the rest of the blocks below ? #include <iostream> using namespace std; // Creating a node class Node { public: string value; Node* next; }; void func1(Node* head) { if (head == NULL) { return; } cout << " " << head->value; func1(head->next); } int main() { Node* head; Node* one = NULL; Node* two = NULL; Node* three = NULL; // allocate 3 nodes in the heap one = new Node(); two = new Node(); three = new Node(); // Assign value values one->value = "A"; two->value = "B"; three->value = "C"; // Connect nodes one->next = two; two->next = three; three->next = NULL; func1(one); return 0; }
Let's see what is happening behind the scenes. Example; Linked List: head -> A -> B -> C -> NULL; void func1(Node* head) { if (head == NULL) { return; } cout << " " << head->value; func1(head->next); } Iteration 1: Head is Not NULL, So it its prints A, now it called func1(head->next) recursively. Iteration 2: Head is Not NULL, So it its prints B, now it called func1(head->next) recursively. Iteration 3: Head is Not NULL, So it its prints C, now it called func1(head->next) recursively. Iteration 4: Head is NULL, So it it returned from the function and you got the output as A B C. Scenario 2: Suppose you first write the recursive call and then the print statement head will first reach the end and from then it will print. So the output will be C B A void func1(Node* head) { if (head == NULL) { return; } func1(head->next); cout << " " << head->value; }
69,941,557
69,941,962
C++ template function to check if a vector of contains the value?
I had planned to implement a kind of INDEX function for all types similar as in FORTRAN. Would this be a correct solution? A little EDIT after comments. template <typename T> bool contains(std::vector<T>& vec, T value){ if (std::any_of(vec.begin(), vec.end(), [value](T j) { return value == j; }))return true; return false; } NB There is a pitfall with float type comparison for generic implementation!
Yes, that is a valid implementation, however I'd write it differently template <std::ranges::input_range R, typename T> requires std::indirect_binary_predicate<ranges::equal_to, ranges::iterator_t<R>, const T*> bool index(R&& range, const T & value){ return std::ranges::find(range, value) != std::ranges::end(range); } This will work for any sequence and any value that can be compared for equality with elements of that sequence. In C++11 there aren't concepts to be explicit about the requirements, but it goes similarly template <typename R, typename T> bool index(R&& range, const T& value) { using std::begin, std::end; return std::find(begin(range), end(range), value) != end(range); }
69,941,946
69,942,149
no viable conversion from 'lambda' to 'void ...'
I need to give a function another function or lambda as a parameter, and this works, more or less. There is an error as soon as I try to define a capture for a lambda in c++14. You can see the sample code here: // this is part of a library (I cannot change it) class SVGElement { //... public: void onclick(void (*handler)(SVGElement *)) { handler(this); } void rotateBy(int angle) {/*...*/} //... }; // my code SVGElement mySvgElement = SVGElement(); // this works mySvgElement.onclick([](SVGElement* clicked){clicked->rotateBy(15);}); // as soon as I define a capture, there is an error int angle = 15; mySvgElement.onclick([angle](SVGElement* clicked){clicked->rotateBy(angle);}); As you can see, part of the problem is that I cannot change part of the code. Is there anything I can do or am I missing something or is the situation hopeless? Here is the error I get: input_line_7:22:22: error: no viable conversion from '(lambda at input_line_7:22:22)' to 'void (*)(__cling_N52::SVGElement *)' mySvgElement.onclick([angle](SVGElement* clicked){clicked->rotateBy(angle);}); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ input_line_7:7:25: note: passing argument to parameter 'handler' here void onclick(void (*handler)(SVGElement *)) { ^
Functions can't have captures. Lambdas can, which means they aren't functions. A lambda with no captures can be converted to a function pointer but a lambda with captures cannot. This code: int angle = 15; mySvgElement.onclick([angle](SVGElement* clicked){clicked->rotateBy(angle);}); is effectively equivalent to: int angle = 15; struct MyLambda { int angle; void operator()(SVGElement* clicked){clicked->rotateBy(angle);} }; mySvgElement.onclick(MyLambda{angle}); and there is no way to treat a MyLambda object as a function pointer, because it's not a function, it's actually an object with variables in it. If the lambda had no captures, you could easily construct a wrapper function like this: void MyLambda_wrapper(SVGElement* clicked) { MyLambda l; l(clicked); } and then you could do mySvgElement.onclick(MyLambda_wrapper); which is effectively what the compiler does. However, this doesn't work with captures, because the wrapper function needs to know what values to put in the captures. Lambdas don't let you do anything new with the language that you couldn't do before. They are just a shortcut to do things you could already do. You do have some options to store the angle, though: If the angle is always 15, you can just hardcode 15. If the angle is the same for all shapes, you can make it a global variable. Often, libraries will leave some member in their data structures for the application to use, often called void *context or void *userdata. You could store the angle in that variable: int angle = 15; mySvgElement.userdata = (void*)angle; mySvgElement.onclick([](SVGElement* clicked){clicked->rotateBy((int)clicked->userdata);}); If you have more than one of these, you'd need to store a struct pointer and remember to free it when the element is destroyed: mySvgElement.userdata = new my_svg_element_data; ((my_svg_element_data*)mySvgElement.userdata)->left_click_angle = 15; ((my_svg_element_data*)mySvgElement.userdata)->right_click_angle = 30; mySvgElement.onclick([](SVGElement* clicked){clicked->rotateBy(((my_svg_element_data*)clicked->userdata)->left_click_angle);}); mySvgElement.onrclick([](SVGElement* clicked){clicked->rotateBy(((my_svg_element_data*)clicked->userdata)->right_click_angle);}); mySvgElement.ondestroy([](SVGElement* destroyed){delete (my_svg_element_data*)destroyed->userdata;}); You could store the angle in your own global std::unordered_map<SVGElement*, int> click_angle;: click_angle[&mySvgElement] = 15; mySvgElement.onclick([](SVGElement* clicked){clicked->rotateBy(click_angle[clicked]);}); mySvgElement.ondestroy([](SVGElement* destroyed){click_angle.erase(destroyed);});
69,941,950
69,942,482
OpenGL Application crashes when accessing Assimp Texture Coordinate Data
I am trying to access the Texture Coordinate of a Cube model made in blender. for (int i = 0; i < mMesh->mNumVertices; i++) { std::cout << mMesh->mTextureCoords[i][0].x << " " << mMesh->mTextureCoords[i][0].y << std::endl; } Why is this happening. The application window launches but the red color background doesnt display. And the first coords also get printed 0 1 How do i solve this. Removing this code doesn't lead to a crash.
This should be: for (int i = 0; i < mMesh->mNumVertices; i++) { std::cout << mMesh->mTextureCoords[0][i].x << " " << mMesh->mTextureCoords[0][i].y << std::endl; } Looks like you messed up the first and second array arguments. Also, it is good practice to check if the mesh has texture coordinates or not. Then the code becomes if (mMesh->HasTextureCoords(0)) //HasTextureCoords is an assimp function { for (int i = 0; i < mMesh->mNumVertices; i++) { std::cout << mMesh->mTextureCoords[0][i].x << " " << mMesh- >mTextureCoords[0][i].y << std::endl; } }
69,942,040
69,942,104
Extract first template parameter type from any object
Suppose I had a templated object in C++ Test<T> and I wanted to find out what the T value is so that when I pass Test<T> as a template argument to TestWrapper<Test<T>>, I can declare a variable called T extradata in the object TestWrapper that is the same as Test's T type. How can I achieve this by only modifying TestWrapper (i.e. making no changes to Test struct) ? Additionally is it possible to modify it so that it will extract from any object that takes 1 template parameter e.g. foo<T>, bar<T>, rather then just Test<T>>? Thanks in advance. template<typename T> struct Test { T value; }; //template -> extract first type parameter from any object as T struct TestWrapper { T extradata; }; int main() { TestWrapper<Test<int>> temp; temp.extradata = 123; // temp.extradata is a int, deduced from Test<int> }
You can use partial template specialization to do that. template<typename T> struct Test { T value; }; template <typename T> struct TestWrapper; template <template <typename> typename Outer, typename T> struct TestWrapper<Outer<T>> { T extradata; }; int main() { TestWrapper<Test<int>> temp; temp.extradata = 123; // temp.extradata is a int, deduced from Test<int> } In this example we have not defined any default definition for TestWrapper, so it will fail to compile if you give something that does not match the specialization.
69,942,076
69,942,201
What template parameter do I use? (C++ conceptual question)
I am going through the book C++ Crash Course by Josh Lospinoso and have been compiling the code in the lessons along the way. I'm having trouble with the following code (which is a simplified version of one of the examples in the book). struct SmallStruct {}; template <typename T> struct BigStruct { BigStruct(const T& arg) : arg{arg} {}; private: const T& arg; }; int main() { BigStruct main_struct{[](const SmallStruct&) {}}; } The main part of this code I don't understand is the statement in main(), specifically constructing with a lambda function. I know the code doesn't compile because when instantiating the BigStruct object in main() it is lacking a template parameter. I've tried <SmallStruct>, <SmallStruct&> as parameters but neither compile. If anyone could explain what is going on it would be really beneficial for my learning.
In the "old" days the way was to use a make_... helper function to get the template parameter deduced from a function parameter: struct SmallStruct {}; template <typename T> struct BigStruct { BigStruct(const T& arg) : arg{arg} {}; private: const T& arg; }; template <typename T> BigStruct<T> make_big_struct(const T& t){ return {t}; } int main() { auto main_struct = make_big_struct([](const SmallStruct&) {}); } Since C++17 there is CTAD (class template argument deduction) and your code compiles without error as is because T can be deduced from the parameter to the constructor (https://godbolt.org/z/oWrnc6bah).
69,942,288
69,942,536
How to use a const pair from one cpp file in another
I have 2 structs: S and R. R has an instance of type S. In S there is defined a const pair that I want to use also in R but I get the following errors. S.hpp:11:12: error: redefinition of ‘const conf n1::n2::def1’ 11 | const conf def1 = std::make_pair(10, 2); | ^~~~ These are the structs and main function #include <string> #include <iostream> #include <utility> #include <memory> namespace n1 { namespace n2 { typedef std::pair<uint32_t, uint32_t> conf; const conf def1 = std::make_pair(10, 2); const conf def2 = std::make_pair(20, 4); struct S { int x; inline void print(); }; using Sptr = std::shared_ptr<S>; } } #include "S.hpp" namespace n1 { namespace n2 { void S::print() { std::cout<<"S-print\n"; } } } include "S.hpp" #include <memory> namespace n1 { namespace c1 { struct R { R(n1::n2::Sptr s); void r(); n1::n2::Sptr s_; }; } } #include "R.hpp" namespace n1 { namespace c1 { R::R(n1::n2::Sptr s):s_(s){} void R::r() { n1::n2::conf c; std::cout<<"---s.first: " << c.first; } } } #include <iostream> #include "R.cpp" #include "S.cpp" #include <memory> int main() { auto s = std::make_shared<n1::n2::S>(); auto r = std::make_shared<n1::c1::R>(s); r->r(); s.print(); return 0; }
I have made 3 changes in your program and it compiles: Change 1 Added header guards. This is my habit(and advice) to add the header guards whenever i don't see in headers. So now your headers look like: S.hpp #ifndef S_H #define S_H #include <string> #include <iostream> #include <utility> #include <memory> namespace n1 { namespace n2 { typedef std::pair<uint32_t, uint32_t> conf; const conf def1 = std::make_pair(10, 2); const conf def2 = std::make_pair(20, 4); struct S { int x; inline void print(); }; using Sptr = std::shared_ptr<S>; } } #endif R.hpp #ifndef R_H #define R_H #include "S.hpp" #include <memory> namespace n1 { namespace c1 { struct R { R(n1::n2::Sptr s); void r(); n1::n2::Sptr s_; }; } } #endif Change 2 In main.cpp i have changed #include "R.cpp" and #include "S.cpp" to #include "R.hpp" and #include "S.hpp" respectively. So your main.cpp now looks like: main.cpp #include <iostream> #include "R.hpp" #include "S.hpp" #include <memory> int main() { auto s = std::make_shared<n1::n2::S>(); auto r = std::make_shared<n1::c1::R>(s); r->r(); //s.print(); return 0; } Change 3 Note in the main.cpp i have commented our the statement s.print(); because s is of type shared_ptr which has no print method. The program now compiles and gives output as can be seen here.
69,942,685
69,942,977
How to get any additional info about the occurred error in Bison?
I'm just starting with Flex/Bison and I'm trying to translate pascal-look-alike variables declarations like this: VAR V1: INT; V2: INT; END_VAR into C variables declarations like this: int main () { int V1; int V2; } I wrote lex- and yacc-files describing needed grammar, then compiled it with flex, bison and gcc utilities in cmd. It's all done without error. But when I try to push a code file with several variables declarations (same as the first code example) in executable file, I only get "syntax error" written in cmd. I don't know how to get any additional info about this error, though the code has to be very simple. --- UPDATE --- I used Öö Tiib answer and it helped to get info about the error. I was looking for a mistake in my lex-file: the program was expecting ':' character, but it faced some undefined character. That was because the space character in regular expression [; j] caused lexer to identify it as the token, though white spaces should be ignored as written in regular expression [ \t\n]. That's how lex-file shall look then: %{ #include "parser.tab.h" #include <string.h> %} %% [a-z]([a-z]|[0-9])* { strcpy (yylval.var, yytext); return ID; } "VAR" { return VAR; } "END_VAR" { return END_VAR; } "INT" { return INT; } [:;] { return *yytext; } [ \t\n]; %% int yywrap () { return 1; }
For more informative error strings you need %error-verbose in yacc file. Perhaps like that in your file: %{ #include <stdio.h> extern FILE * yyout; extern char * yylex (); void yyerror (char *s); %} %error-verbose %union { int number; char var [10]; } ... More information on error analysis are in manual, your question does not indicate how far you are there with your studies.
69,943,142
69,945,058
Cyclic Reference issue with includes for friend class
I have 2 classes: S and R. R has an intance of type S. I want to have R as friend class to have acces to S private methods. Unfortunately I couldn't build it. Please help me how can I solve this. I tried forward declaration in more ways but it didn't work. I get the following error R.hpp:12:15: error: ‘n1::n2’ has not been declared 12 | R(n1::n2::Sptr s); Thanks a lot in advance!. S.hpp: #ifndef S_H #define S_H #include <memory> namespace n1 { namespace n2 { class S { friend class c1::R; int x; inline void print(); }; using Sptr = std::shared_ptr<S>; } } #endif S.cpp: #include "S.hpp" #include "R.hpp" namespace n1 { namespace n2 { void S::print() { std::cout<<"S-print\n"; } } } R.hpp: #ifndef R_H #define R_H #include <memory> namespace n1 { namespace c1 { class S; struct R { R(n1::n2::Sptr s); void r(); n1::n2::Sptr s_; }; } } #endif R.cpp: #include "R.hpp" #include "S.hpp" namespace n1 { namespace c1 { R::R(n1::n2::Sptr s):s_(s) {} void R::r() { s_->print(); } } } main.cpp: #include <iostream> #include "R.hpp" #include "S.hpp" #include <memory> int main() { auto s = std::make_shared<n1::n2::S>(); auto r = std::make_shared<n1::c1::R>(s); r->r(); //s.print(); return 0; }
You can get the program to work(compile) by using the following modifications in your files: S.hpp #ifndef S_H #define S_H #include <memory> namespace n1 { namespace c1 { class R; } } namespace n1 { namespace n2 { class S { friend class c1::R; int x; void print(); }; // using Sptr = std::shared_ptr<S>; } } #endif S.cpp #include "S.hpp" //#include "R.hpp" #include <iostream> namespace n1 { namespace n2 { void S::print() { std::cout<<"S-print\n"; } } } R.hpp #ifndef R_H #define R_H #include <memory> namespace n1 { namespace n2 { class S; using Sptr = std::shared_ptr<S>; } } namespace n1 { namespace c1 { class S; struct R { R(n1::n2::Sptr s); void r(); n1::n2::Sptr s_; }; } } #endif R.cpp #include "R.hpp" #include "S.hpp" namespace n1 { namespace c1 { R::R(n1::n2::Sptr s):s_(s) {} void R::r() { s_->print(); } } } The output of the above program can be seen here.
69,943,562
69,943,913
Passing const char* in variadic template argument list results in linker errors
I have following template class constructor for an exception class: MyCustomException.h: template<typename ... Args> MyCustomException(const Message& msg, const char* fileName, int line, Args&& ... args); MyCustomException.cpp: template<typename ... Args> MyCustomException(const Message& msg, const char* fileName, int line, Args&& ... args) { // random magic here } Now, when I am trying to pass it a const char* (e.g. in main.cpp): #include "MyCustomException.h" // ... void myFunc() { try { // ... const Message m { id, msg }; const char* mychar { "test string" }; if (someCondition) { throw MyCustomException(m, __FILE__, __LINE__, mychar); } catch (MyCustomException& e) { // ... } } // ... int main() { myFunc(); } I keep getting a linker error LNK2019 (unresolved external symbol): public: __cdecl MyCustomException::MyCustomException<char const *>(class Message const &,char const *,int,char const *) When passing it a string literal, everything works just fine. What's the deal with variadic template parameters and const char*?
The problem was with defining the template constructor inside a separate .cpp file. As G.M. linked to this post in the comments, template members should be implemented in the header file or, when defined in the .cpp file, at least be defined explicitly for each instance.
69,943,708
69,943,896
return 2D array in C++
I am kind of new to C++ and I was doing a physics simulation in python which was taking forever to finish so I decided to switch to C++, and I don t understand how to make a function which will return a 2D array (or 3D array) #include <iostream> #include <cmath> // #include <complex> // using namespace std; double** psiinit(int L, int n, double alpha){ double yj[400][400] = {}; for (int j = 0; j < n; j++) { double xi[400] = {}; for (int i = 0; i < n; i++) { xi[i] = exp(-(pow((i-(L/4)), 2) + (pow((j-(L/4)), 2)))/alpha) / (sqrt(2)*3.14159*alpha); }; yj[j] = xi; }; return yj; } int main(){ int L = 10; int n = 400; int nt = 200*n; double alpha = 1; double m = 1; double hbar = 1; double x[n] = {}; double y[n] = {}; double t[nt] = {}; double psi[nt][n][n] = {}; psi[0] = psiinit(L, n, alpha); cout << psi <<endl; return 0; } I have look for answers but it doesn't seems to be for my kind of problems Thanks
If you're new to c++ you should read about the concepts of heap and stack, and about stack frames. There are a ton of good resources for that. In short, when you declare a C-style array (such as yj), it is created in the stack frame of the function, and therefore there are no guarantees about it once you exit the frame, and your program invokes undefined behavior when it references that returned array. There are 3 options: Pass the array to the function as an output parameter (very C-style and not recommended). Wrap the array in a class (like std::array already does for you), in which case it remains on the stack and is copied to the calling frame when returned, but then its size has to be known at compile time. Allocate the array on the heap and return it, which seems to me to best suit your case. std::vector does that for you: std::vector<std::vector<double>> psiinit(int L, int n, double alpha){ std::vector<std::vector<double>> yj; for (int j = 0; j < n; j++) { std::vector<double> xi; for (int i = 0; i < n; i++) { const int value = exp(-(pow((i-(L/4)), 2) + (pow((j-(L/4)), 2)))/alpha) / (sqrt(2)*3.14159*alpha); xi.push_back(value); } yj.push_back(xi); } return yj; } If you're concerned with performance and all of your inner vectors are of a fixed size N, it might be better to use std::vector<std::array<double, N>>.
69,943,854
69,944,428
Factory for threads in C++
I am currently trying to create a sort of "factory" pattern in a class, whose instances should be Threads that have their own certain operation procedure. I have currently declared a global variable isFinished in order to end the operation of the worker thread, however, somehow the operation does not stop after the variable state is changed, and the worker thread does not do the std::thread::join() operation in order to finish working. I am new to threads, and in C++ in general and I don't really know what is wrong so any help would be greatly appreciated. Here is the code: \\main.cpp #include <iostream> #include <thread> #include <atomic> #include "Sender.h" int main() { isFinished = false; //set false for worker thread Sender mSender; //Create thread object for worker std::cin.get(); //Trigger by pressing enter isFinished = true; //exit worker while loop mSender.join(); //wait for the worker thread to finish execution } \\sender.cpp #include <iostream> #include <thread> #include <atomic> #include "Sender.h" void Sender::SenderWorkflow() { while (!isFinished) { std::cout << "Working... \n"; } } \\sender.h #include <iostream> #include <thread> #include <atomic> static std::atomic<bool> isFinished; class Sender { public: std::thread worker; Sender() : worker(&Sender::SenderWorkflow, this) { } void SenderWorkflow(); void join() { worker.join(); \\std::thread::join() } };
The problem is that you are using a static variable in the global scope. static in a namespace scope is used to hide the variable or function in the object file so that the linker can't see it while linking another object file for another cpp file. In practice static is used only inside the cpp file itself. Since you declared it inside the header each translation unit that includes it will get a different instance of the variable because the linker can't see the same variable across objects file. To solve this : 1- move the declaration of the static variable to the cpp file and make an accessor function in the header file: \\sender.h #include <atomic> const std::atomic<bool>& checkIsFinished(); void setFinished(); \\sender.cpp static std::atomic<bool> isFinished; const std::atomic<bool>& checkIsFinished() { return isFinished; } void setFinished() { isFinished = true; } 2- or use inline variable (since c++17) in the header file: \\sender.h #include <atomic> inline std::atomic<bool> isFinished; 3 - or better and the correct design : make the variable local as member of the class, the less global variables the better ! \\sender.h #include <atomic> class Sender { public: std::thread worker; Sender() : worker(&Sender::SenderWorkflow, this) { } void SenderWorkflow(); void join() { isFinished = true; worker.join(); \\std::thread::join() } private: std::atomic<bool> isFinished = false; };
69,945,027
69,945,313
Running the same code, old computers are as fast as new ones, is that true?
I've been learning about parallel programming in c++ and I came across materials from a university. In the lecture they stated : "With old code, a computer from 2021 is not any faster than a computer from 2000. In this course, we will learn how to write new code that is designed with modern computers in mind." LINK Waiting for answers from the professor, I thought to post my questions here. Is that true? and in what conditions ? what do they mean by old code? sequential code? In the lecture, they talk about the clock speed of the CPU and they mentioned that it hasn't been changed since the 2000s. Is that enough to say that an old computer is as fast as a new one?
Is that true? and in what conditions ? It is true that the clock speed of processors hasn't increased since ~2005 (and went down in the mean time). That isn't to say that single core wall-clock performance hasn't improved. It hasn't been the case for long before then that each instruction took a single clock to process. There is a pipeline of instructions, and multiple calculations are "in-flight" at a time. A recent processor will take fewer cycles to execute the same instruction stream than an older processor. Memory has also increased in speed, and processors have more on-die memory. Programs and data that didn't fit in the caches of a P4 might fit on a current-gen Core, and when they do have to fetch from RAM they are waiting less. What is true is that a major improvement in processors since that era is the multiplication of cores on a single die, and using that performance is not as simple as "waiting for next year's faster processor"
69,945,245
69,947,968
Understanding Makefile rule
I have been debugging a linking error for specific target (android), for all other targets, build is successful. Error is something like Test.cpp:29:57: fatal error: linux/ethtool.h: No such file or directory compilation terminated. make: *** [../../../makefiles/rules.makefile:1012: android-arm-r/Test.o] Error 1 and build command is: make DEBUG=no TARGET=android I checked this rules.makefile's 1012 line: $(OBJDIR)/%.$(OBJ_SUFFIX): %.cpp $(OBJDIR)/%.d @$(cpp_PRECOMPILE) $(cpp_COMMAND) $< @$(cpp_POSTCOMPILE) Now, as typical make rule pattern, I can understand that, TARGET is $(OBJDIR)/%.$(OBJ_SUFFIX) PREREQUISITES are %.cpp $(OBJDIR)/%.d (Source files, which would be mostly Test.cpp, being the only cpp file in that dir) RECIPE is @$(cpp_PRECOMPILE) $(cpp_COMMAND) $< @$(cpp_POSTCOMPILE) Here, looking at other files, I could see, cpp_PRECOMPILE is : cpp_COMMAND is gcc -x c++ cpp_PRECOMPILE is : So that makes the RECIPE, somewhat like: @: /opt/android-arm-r9/bin/arm-linux-androideabi- gcc -x c++ $< @: Now, I am not able to understand: What is @$ for? $< is automatic variable holding prerequisite name. But overall what action this recipe is trying to do? When no TARGET is given (default is linux) make CPU=x86_64 DEBUG=no works perfectly. But when TARGET=android, it fails. make CPU=x86_64 DEBUG=no TARGET=android
What is @$ for? @$ is not a unit. The @ is a prefix that suppresses the command's output from being forwarded to make's output. The $ is the beginning of a variable reference ($(cpp_PRECOMPILE)) which expands to a command to run. $< is automatic variable holding prerequisite name. But overall what action this recipe is trying to do? More specifically, $< expands to the name of the first prerequisite. This matters in your case, since the rule designates multiple prerequisites. The variable names appearing in the recipe give a pretty clear indication of what the recipe is supposed to do: $(cpp_PRECOMPILE) -- some kind of step preparing for compilation. That might be anything or nothing; it presumably depends on values of other variables, and maybe on other factors as well. $(cpp_COMMAND) $< -- compile the source file named by the first prerequisite. Presumably with a C++ compiler. $(cpp_POSTCOMPILE) -- some kind of post-processing, cleanup, or followup step to be performed after compilation. As with the pre-compile step, that could be anything or nothing, with the details depending on other parts of the makefile. When no TARGET is given (default is linux) make CPU=x86_64 DEBUG=no works perfectly. But when target=android, it fails. make CPU=x86_64 DEBUG=no TARGET=android TARGET (and DEBUG and CPU) are details specific to your particular makefile, not features of make generally. We can't speak to the specifics of their effects. However, these error messages ... Test.cpp:29:57: fatal error: linux/ethtool.h: No such file or directory compilation terminated. make: *** [../../../makefiles/rules.makefile:1012: android-arm-r/Test.o] Error 1 ... present a reasonably clear picture of what the immediate problem is: file Test.cpp, as it is being compiled, attempts to #include a C header file linux/ethtool.h, which file is not found in the cross environment supporting your cross build. That the error does not manifest when you perform a different kind of build is not particularly relevant. You should review the build requirements documentation for the project. It may specify particular required packages, which, for a cross build such as you are trying to perform, would probably need to be installed in the cross environment. Possibly kernel headers. You may also want to seek assistance from the maintainers of the project.
69,945,844
69,946,626
Why passing `printf` as template function argument succeeds but `cos` failed (msvc 19)?
I am playing with online c++ compilers a little bit on link. But the code snippet below got failed when compiled with msvc v19.latest. #include <iostream> #include <cmath> #include <cstdio> template<class F, class...L> void test(F f, L...args) { std::cout<< "res = " << f(args...) << '\n'; } int main() { test(cos, 0.1); #1 test(printf, "%s", "aaa"); #2 } How could it be that line #2 is ok and line #1 can't get a pass? MSVC is happy with the following code but this time it's GCC's turn to reject it. MSVC's iostream file includes cmath header and GCC #undefs cos :) #include <stdio.h> #include <math.h> //#include <iostream> template<class F, class...L> void test(F f, L...args) { f(args...); } int main() { test(cos, 0.1); test(printf, "%s", "aaa"); } Since c++20, there's another issue raised in the second answer and has been addressed in this question link
It is failing because cos is an overloaded function in msvc. This means that there are at least 3 different versions of cos: float cos(float arg); double cos(double arg); long double cos(long double arg); The compiler has no way of guessing which one you are trying to use, but you can give it a hand by using static_cast like the following: int main() { test(static_cast<double(*)(double)>(cos), 0.1); test(printf, "%s", "aaa"); }
69,946,062
69,947,643
How to duplicate the vowels between two consonants in a string?
I want to duplicate the vowels between two consonants in a string. Input : informatics Output : infoormaatiics I have made an attempt below: #include<bits/stdc++.h> #define ios ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); using namespace std; void solution(){ string i; cin >> i; int n = i.size(); string vo = "aeuio"; for(int j=1; j<n-1; j++){ if(vo.find(i[j-1]) >= i.length() && vo.find(i[j]) < i.length() && vo.find(i[j+1]) >= i.length()){ i.insert(j+1 , i[j]); } } cout << i << endl; } int main(){ ios int t; cin >> t; while(t--){ solution(); } return 0; } the problem in my code is in insert because the compiler give me: insert(size_type __pos1, const basic_string& __str,
Here's what I'd write using a regular expression: #include <iostream> #include <regex> std::string solution(std::string i){ std::regex re( "([bcdfghjklmnpqrstvxz])" "([aeiouy])" "([bcdfghjklmnpqrstvxz])"); return std::regex_replace(i, re, "$1$2$2$3"); } int main(){ for (std::string i; std::cin >> i;) { //std::cout << i << " -> " << solution(i) << "\n"; std::cout << solution(i) << "\n"; } } In response to @cigien's comment: std::string solution(std::string i) { std::regex re( "([bcdfghjklmnpqrstvxz])" "([aeiouy])" "(?=[bcdfghjklmnpqrstvxz])"); return std::regex_replace(i, re, "$1$2$2"); } This will also take care of cases where there are "middle consonants" that fence multiple vowels. With random tests: (echo informatics; sort -R /etc/dictionaries-common/words | head -9) | ./sotest infoormaatiics niiceest afteereeffeect Lamaar poortaageed Asuunción's viiviiseection opaaquer inteerruupts Anaabaaptiist's Review of your code The most prominent problem was insert not being called with a suitable set of arguments: https://en.cppreference.com/w/cpp/string/basic_string/insert The closest would be to use overload (3): basic_string& insert( size_type index, const CharT* s, size_type count ); So, basically i.insert(j + 1, i.data() + j, 1); Side notes are that since i is modified, caching size() will lead to some matches not being processed because you abandon the loop early. for(size_t j=1; j<i.size()-1; j++){ fixes that. std::string vo = "aeuio"; Seems pretty inefficient. Why not use a lambda - both more expressive and more efficient: static inline bool is_vowel(char ch) { switch (ch) { case 'a': case 'e': case 'u': case 'i': case 'o': case 'A': case 'E': case 'U': case 'I': case 'O': return true; default: return false; } } And then maybe: std::string solution(std::string input) { auto cons_around = [&input](int index) { return not(is_vowel(input.at(index - 1)) // or is_vowel(input.at(index + 1))); }; for (size_t i = 1; i < input.size() - 1; i++) { if (cons_around(i) and is_vowel(input.at(i))) input.insert(i + 1, input.data() + i, 1); } return input; } Strictly speaking, this is not satisfying the requirements (even though it now recognizes uppercase vowels) because it assumes everything non-vowel is consonant (interpunction and numeric etc. exist). But the result is closer: http://coliru.stacked-crooked.com/a/f9db3887705a3b4c #include<string> #include<iostream> static inline bool is_vowel(char ch) { switch (ch) { case 'a': case 'e': case 'u': case 'i': case 'o': case 'A': case 'E': case 'U': case 'I': case 'O': return true; default: return false; } } std::string solution(std::string input) { auto cons_around = [&input](int index) { return not(is_vowel(input.at(index - 1)) // or is_vowel(input.at(index + 1))); }; for (size_t i = 1; i < input.size() - 1; i++) { if (cons_around(i) and is_vowel(input.at(i))) input.insert(i + 1, input.data() + i, 1); } return input; } int main(){ int t; std::cin >> t; std::string i; while (t-- && std::cin >> i) { std::cout << solution(i) << "\n"; } } Prints foo baar quux
69,946,460
69,946,565
Making a simple guessing game between 0 and 100, but game ends after 2 guesses
the code is in swedish btw. int nyttal(int n){ int nyttal = rand() % 100 + 1; return rand() % nyttal; } //Lak Lägg void utforEnSpelomgang(){ const int n =100; const int datornstal = nyttal(n); int antalUtfardaGissningar = 0; //number of guesses made by user cout << "Datorn tänker på ett tal mellan noll och " << n << ". Gissa vilket!" << endl; int g; cin >> g; if(g < datornstal){ //if g is smaller than the programs number it will tell you that your guess is smaller cout << "Mindre" << endl; ++antalUtfardaGissningar; cout << "Antal utfärde gissningar: " << antalUtfardaGissningar << endl; cin >> g; } if(g > datornstal){ //user guessed a bigger number cout << "Större" << endl; ++antalUtfardaGissningar; cout << "Antal utfärda gissningar: " << antalUtfardaGissningar << endl; cin >> g; } if(g == datornstal){ cout << "Du gissade rätt" << endl; ++antalUtfardaGissningar; cout << "Antal utfärda gissningar: " << antalUtfardaGissningar << endl; } //Lägg } Everytime i run the code the game ends after 2 guesses and on the second one doesnt even output the cout line ive written. How do i get the code to keep running until the user has guessed right?
You can use/add a while loop as shown void utforEnSpelomgang(){ const int n =100; const int datornstal = nyttal(n); int antalUtfardaGissningar = 0; cout << "Datorn tänker på ett tal mellan noll och " << n << ". Gissa vilket!" << endl; int g; cin >> g; while(g!= datornstal)//added this { if(g < datornstal){ //if g is smaller than the programs number it will tell you that your guess is smaller cout << "Mindre" << endl; ++antalUtfardaGissningar; cout << "Antal utfärde gissningar: " << antalUtfardaGissningar << endl; cin >> g; } if(g > datornstal){ //user guessed a bigger number cout << "Större" << endl; ++antalUtfardaGissningar; cout << "Antal utfärda gissningar: " << antalUtfardaGissningar << endl; cin >> g; } if(g == datornstal){ cout << "Du gissade rätt" << endl; ++antalUtfardaGissningar; cout << "Antal utfärda gissningar: " << antalUtfardaGissningar << endl; break;//added this } } //Lägg } In the above program i have added 2 things. First is a while and second is the break statement for breaking out of the while loop in case the guess is correct. Also if you're wondering why always the same number is generated take a look at How to generate a random number in C++? Note that the last if is redundant and so you can remove it and put the code inside the last if outside the while loop as shown below: while(g!= datornstal)//added this { if(g < datornstal){ //if g is smaller than the programs number it will tell you that your guess is smaller cout << "Mindre" << endl; ++antalUtfardaGissningar; cout << "Antal utfärde gissningar: " << antalUtfardaGissningar << endl; cin >> g; } else if(g > datornstal){ //user guessed a bigger number cout << "Större" << endl; ++antalUtfardaGissningar; cout << "Antal utfärda gissningar: " << antalUtfardaGissningar << endl; cin >> g; } } cout << "Du gissade rätt" << endl; ++antalUtfardaGissningar; cout << "Antal utfärda gissningar: " << antalUtfardaGissningar << endl;
69,946,646
69,946,827
Adding library dependencies to interface libraries in cmake
I have the following cmake file cmake_minimum_required(VERSION 3.16) find_package(fmt) add_library(mylib INTERFACE ) add_dependencies(mylib fmt::fmt-header-only) target_compile_features(mylib INTERFACE cxx_std_20) target_include_directories(mylib INTERFACE .) add_executable(test_exe test_exe.cpp) target_link_libraries(test_exe PUBLIC mylib) But fmt is not linked against test_exe unless I explicitly add it to the dependencies. Am I defining the dependencies of mylib wrong? The error is the following and it goes away if I add fmt::header-only to the link libraries of test_exe fatal error: 'fmt/format.h' file not found #include <fmt/format.h> ^~~~~~~~~~~~~~
add_dependencies(mylib fmt::fmt-header-only) simply makes sure that the target fmt::fmt-header-only is up to date before mylib is built. It doesn't link fmt::fmt-header-only regardless of the target type of mylib. Linking is done via target_link_libraries target_link_libraries(mylib INTERFACE fmt::fmt-header-only)
69,946,860
70,732,246
How to memory-map a PCI BAR using PCIDriverKit?
How to memory-map a PCI Base Address Register (BAR) from a PCIDriverKit driver (DEXT) to a userspace application? Memory-mapping from a driver extension to an application can be accomplished by implementing the IOUserClient::CopyClientMemoryForType in the user client subclass (on the driver side) and then calling IOConnectMapMemory64 (from the user-space application side). This has been very nicely and thoroughly explained in this related answer. The only missing bit is getting an IOMemoryDescriptor corresponding to the desired PCI BAR in order to return it from the CopyClientMemoryForType implementation. Sample code Asked another way, given the following simplified code, what would be the implementation of imaginaryFunctionWhichReturnsTheBARBuffer? kern_return_t IMPL(MyUserClient, CopyClientMemoryForType) //(uint64_t type, uint64_t *options, IOMemoryDescriptor **memory) { IOMemoryDescriptor* buffer = nullptr; imaginaryFunctionWhichReturnsTheBARBuffer(ivars->pciDevice /* IOPCIDevice */, kPCIMemoryRangeBAR0, &buffer); *memory = buffer; return kIOReturnSuccess; } In the previous code ivars->pciDevice refers to a ready-to-use IOPCIDevice (e.g.: it has been succesfully matched, opened and configured according to latest best practices). This means it's already possible to use the various configuration and memory read/write methods to access explicit offsets from the desired PCI BAR memory. What's missing (or unclear) is how to use those APIs (or equivalent ones) to map the entire buffer corresponding to a PCI BAR to a user-space application. Random notes that might or might not be relevant This answer from the related question: How to allocate memory in a DriverKit system extension and map it to another process? contains the following quote: [...] The returned memory descriptor need not be an IOBufferMemoryDescriptor as I've used in the example, it can also be a PCI BAR or whatever. This is exactly what I want to do, so at least it sounds like it should be possible. The only remaining question is how to implement it. A similar question has been posted on the Apple forums and even though it hasn't received any answers yet (as of the time of this writing), it does contain some useful pointers. It looks like there is a private function in PCIDriverKit with the following signature: virtual kern_return_t IOPCIDevice::_CopyDeviceMemoryWithIndex(uint64_t memoryIndex, IOMemoryDescriptor** memory, IOService* forClient) It's hard to tell what it's supposed to do exactly (since it is undocumented), but the signature does seem to match with the function I'm looking for. However, trying to use it always results in an error code (similar to the one reported in the original forum post). The error code seems to be different depending on which argument is passed as IOService *forClient). Another good point from that post is that there is a getDeviceMemoryWithIndex available to kernel extensions (KEXT) which could be used to accomplish what we need (if the driver was implemented as a PCI kernel extension which seems to be deprecated now). However, this function doesn't seem to be available to driver extensions (DEXT). So another question of framing this question could be: What's the equivalent getDeviceMemoryWithIndex for PCIDriverKit driver extensions?
Turns out IOPCIDevice::_CopyDeviceMemoryWithIndex was indeed the function needed to implement this (but the fact that it's private is still an inconvenient). Sample code Bellow is some sample code showing how this could be implemented (the code uses MyDriver for the driver class name and MyDriverUserClient for the user client). Relevant sections from MyDriver.cpp implementation: struct MyDriver_IVars { IOPCIDevice* pciDevice = nullptr; }; // MyDriver::init/free/Start/Stop/NewUserClient implementation ommited for brevity IOMemoryDescriptor* MyDriver::copyBarMemory(uint8_t barIndex) { IOMemoryDescriptor* memory; uint8_t barMemoryIndex, barMemoryType; uint64_t barMemorySize; // Warning: error handling is omitted for brevity ivars->pciDevice->GetBARInfo(barIndex, &barMemoryIndex, &barMemorySize, &barMemoryType); ivars->pciDevice->_CopyDeviceMemoryWithIndex(barMemoryIndex, &memory, this); return memory; } Relevant sections from MyDriverUserClient.cpp implementation: struct MyDriverUserClient_IVars { MyDriver* myDriver = nullptr; }; // MyDriverUserClient::init/free/Start/Stop implementation ommited for brevity kern_return_t IMPL(MyDriverUserClient, CopyClientMemoryForType) //(uint64_t type, uint64_t *options, IOMemoryDescriptor **memory) { *memory = ivars->myDriver->copyBARMemory(kPCIMemoryRangeBAR0); return kIOReturnSuccess; } Additional Resources A complete implementation that uses this pattern can be found in the ivshmem.dext project (which implements a macOS driver for IVSHMEM).
69,946,945
69,947,428
Malloc space for a pointer of array in C++
I need to work upon a variable number of fixed-size arrays. More specifically, N points in a K-dimensional space, where I know K beforehand, but I don't know N at compile time. So I want to use a pointer to the fixed-size array, and allocate space for N K-dimensional points at runtime. In C, I can allocate the said pointer with malloc. Example test.c below, where dimension is 3 for simplicity: #include <stdlib.h> #include <stdio.h> #define DIMENSIONS 3 typedef float PointKDimensions[DIMENSIONS]; void do_stuff( int num_points){ PointKDimensions *points; points = malloc(num_points * sizeof(PointKDimensions)); points[5][0] = 0; // set value to 6th point, first dimension points[5][1] = 1.0; // to second dimension points[5][2] = 3.14; // to third dimension return; } int main(){ do_stuff(10); // at run-time I find out I have 10 points to handle return 0; } I can compile this with gcc test.c without errors, and run without segmentation faults. However, if I try to achieve the same behavior with C++ mv test.c test.cpp, followed by g++ test.cpp, I get: test.cpp: In function ‘void do_stuff(int)’: test.cpp:10:18: error: invalid conversion from ‘void*’ to ‘float (*)[3]’ [-fpermissive] 10 | points = malloc(num_points * sizeof(float) * DIMENSIONS); | ~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | void* Searching up, I found that C++ does not do implicit conversions for malloc, so I changed the malloc to: points = (float*) malloc(num_points * sizeof(float) * DIMENSIONS); And then the error becomes: test.cpp: In function ‘void do_stuff(int)’: test.cpp:10:12: error: cannot convert ‘float*’ to ‘float (*)[3]’ in assignment 10 | points = (float*) malloc(num_points * sizeof(float) * DIMENSIONS); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | float* But I could not find a way to do the appropriate cast/conversion to solve this error. E.g., (float**) is also not the same as float(*)[3]. Any suggestions on how to allocate space for a pointer to fixed-sized arrays in C++?
You need to cast the result of malloc as PointKDimensions* not as a float*: typedef float PointKDimensions[DIMENSIONS]; void do_stuff( int num_points){ PointKDimensions *points; points = (PointKDimensions*)malloc(num_points * sizeof(PointKDimensions)); points[5][0] = 0; // set value to 6th point, first dimension points[5][1] = 1.0; // to second dimension points[5][2] = 3.14; // to third dimension return; } Or better, use C++'s built-in container for dynamically sized arrays, std::vector: vector<vector<float>> points; void do_stuff( int num_points){ points.resize(num_points, vector<float>(k)); // assuming k = number of dimensions. points[5][0] = 0; // set value to 6th point, first dimension points[5][1] = 1.0; // to second dimension points[5][2] = 3.14; // to third dimension return; }
69,946,976
69,947,120
sqrt() c++ and math.sqrt() python
i am new at python and i had this precision problem with python which i did not have before with c++, the code is for python import math def f(x): return math.sqrt(x) print((38 / (math.sqrt(38) * math.sqrt(38)))) print(38 / (f(38) * f(38))) print(math.acos(38 / (math.sqrt(38) * math.sqrt(38)))) print(math.acos(38 / (f(38) * f(38)))) the result is Traceback (most recent call last): File "C:\Users\dell\PycharmProjects\pythonProject2\main.py", line 10, in <module> print(math.acos(38 / (math.sqrt(38) * math.sqrt(38)))) ValueError: math domain error 1.0000000000000002 1.0000000000000002 for c++ #include <iostream> #include <cmath> using namespace std; double f(double x); int main() { cout <<38/(f(38)*f(38))<<endl; cout <<38/(sqrt(38)*sqrt(38))<<endl; cout <<acos(38/(f(38)*f(38)))<<endl; cout <<acos(38/(sqrt(38)*sqrt(38)))<<endl; return 0; } double f(double x) { return sqrt(x); } the result is 1 1 nan 0 this can make crashes
Different programming languages may behave differently when it comes to float arithmetics. It may come to optimisations, internal implementations of functions like acos etc. First, notice that in C++, acos returns the special value nan for values out of range, while in Python it throws the ValueError exception. You can, however, easily get the C++ behavior like this: import math def my_acos(x): try: return math.acos(x) except ValueError: return float("nan") Furthermore, you can add rounding to accept values slightly out of range. Your number has 15 zeroes after the decimal point, so let's round to 15 places (for the sake of demonstration): import math def my_acos(x): try: return math.acos(round(x, 15)) except ValueError: return float("nan") With this modification, your code will produce the results you expect.
69,947,404
69,947,506
C++ function inside function
/*I need to use the result from the (delta) function inside the (sol_ec_II) function for a school assignment.*/ #include <iostream> #include <ctgmath> using namespace std; double delta(double a, double b, double c) { return (b * b) - (4 * a * c);/* so I need to take this value [(b * b) - (4 * a * c)] and use it in sol_ec_II in the places where I wrote "delta". */ } void sol_ec_II(double a, double b, double c) { if (delta < 0) {//here cout << endl << "Polinomul NU are solutii."; } else { double x1 = -1 * b - sqrt(delta);//here double x2 = -1 * b + sqrt(delta);//here } } // I would also need to use the (delta) function inside the (sol_ec_II) so they use the same a, b, c values like this: void sol_ec_II(double a, double b, double c) { delta(a, b, c); if (delta < 0) { cout << endl << "Polinomul NU are solutii."; } else { double x1 = -1 * b - sqrt(delta); double x2 = -1 * b + sqrt(delta); } } //so I don't understand how to get the value that results from delta(a, b, c) and use it inside the if statement and sqrt.
The result "comes out" of the function call at the time you call it. Look, you already know how sqrt works. sqrt is a function! You write sqrt(something) and that calls the function sqrt and it calls the function sqrt with the argument something and then the return value from sqrt gets used in the place where you wrote sqrt(something). e.g. 1 + sqrt(4) calculates 3. Likewise the return value from delta gets used in the place where you wrote delta(a, b, c). If you want to call delta and then call sqrt (i.e. calculate the square root of the delta) you write sqrt(delta(a, b, c)). Obviously, just calculating a number is pretty useless. You probably want to do something with the number, like saving it in a variable or printing it. Examples: cout << "the square root of the delta is " << sqrt(delta(a,b,c)) << endl; cout << "the delta plus one is " << (delta(a,b,c) + 1) << endl; double the_delta = delta(a,b,c); cout << "the delta is " << the_delta << " and the square root of the delta is " << sqrt(the_delta) << endl; if (delta(a,b,c) < 0) cout << "the delta is negative" << endl; else cout << "the delta isn't negative" << endl; Note: Every time the computer runs delta(a,b,c) it calls the delta function. It doesn't remember the calculation from last time. You can see this because if you put cout instructions inside the delta function, they get printed every time the computer runs delta(a,b,c). Of course I will not give you the solution for your program. I hope this helps you understand how functions work.
69,947,545
69,947,822
Seperating C++ Nested Classes into their Own Header Files
new to this site and also C++ but hoping to see some guidance from everyone. I had a pretty fun project idea to learn C++ digging deeper with APIs, classes, references, etc. and currently I have a working example of code where everything exist within the main.cpp file. The issue I am facing is that when i move the classes (inner and outer) to their own respective header files the code no longer compiles. The reason for the nested classes is that the OuterAPI serves as the main entry point to the API and has many lower level APIs that can be then accessed beneath it (people, licenes, roles, etc). This way users of API would only have to create an object for the OuterAPI and then dot notation for underlying resource and method. Here is the working example in the main.cpp #include <iostream> #include <nlohmann/json.hpp> #include <cpr/cpr.h> using json = nlohmann::json; class OuterAPI { private: class InnerAPI { private: OuterAPI& api; public: InnerAPI(OuterAPI& a) :api(a) {} json get() { cpr::Response r = cpr::Get( cpr::Url{ api.baseUrl + "resource" }, cpr::Bearer{ api.token } ); return json::parse(r.text) }; std::string token; std::string baseUrl = ""; public: InnerAPI people; OuterAPI(std::string t) : token(t), people(*this) {} }; int main(int argc, char** argv) { std::string token = ""; OuterAPI api(token); json jsonData = api.people.get(); std::cout << jsonData.dump(4) << std::endl; return 0; } Here is me moving everything to respective header/cpp files OuterAPI.h #pragma once class OuterAPI { private: class InnerAPI; std::string token; std::string baseUrl = ""; public: OuterAPI(std::string t); ~OuterAPI(); InnerAPI* people; }; OuterAPI.cpp #include "WebexAPI.h" #include "PeopleAPI.h" OuterAPI::OuterAPI(std::string t) : token(t) { people = new InnerAPI(*this); } OuterAPI::~OuterAPI() { delete people; } InnerAPI.h #pragma once #include <nlohmann/json.hpp> #include <cpr/cpr.h> #include "OuterAPI.h" using json = nlohmann::json; class OuterAPI::InnerAPI { private: OuterAPI& api; public: InnerAPI(OuterAPI& a); json get(); }; InnerAPI.cpp #include "InnerAPI.h" OuterAPI::InnerAPI::InnerAPI(OuterAPI& a) : api(a) {} json OuterAPI::InnerAPI::get() { cpr::Response r = cpr::Get( cpr::Url{ api.baseUrl + "resource" }, cpr::Bearer{ api.token } ); return json::parse(r.text); main.cpp (finally) - this is where the compiler error occurs at api.people.get() "expression must have class type but has type "OuterAPI::InnerAPI *" int main(int argc, char** argv) { std::string token = ""; OuterAPI api(token); json jsonData = api.people.get(); // COMPILER ERROR "expression must have class type but has type "OuterAPI::InnerAPI *" std::cout << jsonData.dump(4) << std::endl; return 0; } From this I believe the issue is associated with me having to define the InnerAPI object people as a pointer inside of OuterAPI but from here I cant seem to come to a resolution. Also, feel free to critique my design as well, like I say I am new to C++ so want to make sure I can do a good job. Thanks.
In OuterAPI* you have declared people as a member of type InnerAPI*. You can either call your API using api.people->get() or make the member a InnerAPI instead. EDIT: It seems the error, besides the pointer thing, comes from how you handle file includes. I managed to get a working version on REPL.it. I made slight adjustments so I wouldn't have to bring both libraries in so focus on the gist of it. Here it is: OuterAPI.h #pragma once #include <string> class OuterAPI { private: class InnerAPI; std::string token; std::string baseUrl = ""; public: OuterAPI(std::string t); ~OuterAPI(); InnerAPI* people; }; InnerAPI.j #pragma once #include "./OuterAPI.h" class OuterAPI::InnerAPI { private: OuterAPI& api; public: InnerAPI(OuterAPI& a); std::string get(); }; OuterAPI.cpp #include "./OuterAPI.h" #include "./InnerAPI.h" OuterAPI::OuterAPI(std::string t) : token(t) { people = new InnerAPI(*this); } OuterAPI::~OuterAPI() { delete people; } InnerAPI.cpp #include "./OuterAPI.h" #include "./InnerAPI.h" OuterAPI::InnerAPI::InnerAPI(OuterAPI& a) : api(a) {} std::string OuterAPI::InnerAPI::get() { return api.baseUrl + "resource"; }
69,947,598
69,947,821
Convert a function pointer to another having more arguments
Suppose I am trying to use a function which accepts a binary function and calls it with some arguments: typedef double (*BinaryFunction)(double a, double b); typedef double (*UnaryFunction)(double a); // Can't change this double ExternalFunction(BinaryFunction binaryFunction) { return binaryFunction(1, 2); } Now suppose a user of my code is going to provide me with a unary function. My goal is to convert it into a binary function so that I can call ExternalFunction with it: double MyFunction(UnaryFunction unaryFunction) { BinaryFunction binaryFunction = /* want a function (a, b) -> unaryFunction(a + b) */; return ExternalFunction(binaryFunction); } How do I do this? Just to be clear, I understand that this would be easy if the unary function were known at compile time, but it's not - it will be an argument to my function. Thanks in advance. Here's a summary of my attempts. I believe I understand why these don't work, but I'm providing them so you can see what I've been thinking so far. I can't use a lambda, because I'd have to capture UnaryFunction, and capturing lambdas can't be converted to function pointers: double MyFunction(UnaryFunction unaryFunction) { BinaryFunction binaryFunction = [unaryFunction](double a, double b){ return unaryFunction(a + b); }; return ExternalFunction(binaryFunction); } Use std::function ? Can't get that to work either: void MyFunction(UnaryFunction unaryFunction) { std::function<double(double, double)> binaryFunctionTemp = [unaryFunction](double a, double b) { return unaryFunction(a + b); }; BinaryFunction binaryFunction = binaryFunctionTemp.target<double(double, double)>(); ExternalFunction(binaryFunction); } What about a function object? Won't work because we'd need a pointer to a member function: class BinaryFromUnary { public: BinaryFromUnary(UnaryFunction unaryFunction) : unary_(unaryFunction) {}; double operator()(double a, double b) { return unary_(a + b); } private: UnaryFunction unary_; }; void MyFunction(UnaryFunction unaryFunction) { BinaryFromUnary functionObject(unaryFunction); std::function<double(double, double)> binaryFunction = functionObject; ExternalFunction(binaryFunction.target<double(double, double)>()); } Even had a go with std::bind (and probably messed it up): struct Converter { Converter(UnaryFunction unary) : unary_(unary) {} double binary(double a, double b) const { return unary_(a + b); } UnaryFunction unary_; }; void MyFunction(UnaryFunction unaryFunction) { Converter converter(unaryFunction); std::function<double(double, double)> binaryFunction = std::bind( &Converter::binary, converter, _1, _2); ExternalFunction(binaryFunction.target<double(double, double)>()); } Tried a couple of other things along the same lines. Any ideas would be much appreciated.
Use an external variable to hold the unary function. Include standard disclaimers about how inelegant and non-thread safe this is, etc. but at least this is a hack consistent with the stated requirements: #include <iostream> typedef double (*BinaryFunction)(double a, double b); typedef double (*UnaryFunction)(double a); // Can't change this double ExternalFunction(BinaryFunction binaryFunction) { return binaryFunction(1, 2); } namespace foo { thread_local UnaryFunction unaryFunction; } double MyBinaryFunction(double a, double b) { return foo::unaryFunction(a + b); } double MyUnaryFunction(double a) { return 2 * a; } double MyFunction(UnaryFunction unaryFunction) { foo::unaryFunction = unaryFunction; BinaryFunction binaryFunction = MyBinaryFunction; return ExternalFunction(binaryFunction); } int main() { std::cout << MyFunction(MyUnaryFunction) << std::endl; // 6 return 0; }
69,947,908
69,948,121
Why can't lvalue references bind to const "forwarding references"?
"forwarding references" is in quotes because const-qualified forwarding references aren't actually forwarding references, but I wanted to make it clear that I am specifically referring to function templates. Take the following test functions (code is duplicated to avoid : #include <iostream> #include <type_traits> #include <typeinfo> using namespace std; template <typename T, typename U> void print_types() { cout << (is_const_v<remove_reference_t<T>> ? "const " : "") << typeid(T).name() << (is_rvalue_reference_v<T> ? " &&" : is_lvalue_reference_v<T> ? " &" : "") << ", " << (is_const_v<remove_reference_t<U>> ? "const " : "") << typeid(U).name() << (is_rvalue_reference_v<U> ? " &&" : is_lvalue_reference_v<U> ? " &" : "") << endl; } template <typename T> void print_rvalue_reference(T &&t) { print_types<T, decltype(t)>(); } template <typename T> void print_const_rvalue_reference(const T &&t) { print_types<T, decltype(t)>(); } int main() { int i = 1; const int j = 1; print_rvalue_reference(1); // int, int && print_rvalue_reference(i); // int &, int & print_rvalue_reference(j); // const int &, const int & print_const_rvalue_reference(1); // int, const int && print_const_rvalue_reference(i); // error print_const_rvalue_reference(j); // error } First, I wanted to note that print_rvalue_reference(j) only works because print_rvalue_reference never uses t in a non-const context. If this were not the case, the template instantiation would fail. I am confused why the last two calls in main cause errors during compilation. Reference collapsing allows using T = int &; const T && to become int & and using T = const int &; const T && to become const int &, which means print_const_rvalue_reference<int &>(i) and print_const_rvalue_reference<const int &>(j) are valid. Why does print_const_rvalue_reference(j) deduce T to be int instead of const int & when print_rvalue_reference(j) does deduce T to be const int &? Are (true) forwarding references special-cased to yield int & instead of int as part of its deduction guide?
Actual forwarding references are indeed special-cased to deduce a reference type. See [temp.deduct.call]/3: If P is a cv-qualified type, the top-level cv-qualifiers of P's type are ignored for type deduction. If P is a reference type, the type referred to by P is used for type deduction. ... If P is a forwarding reference and the argument is an lvalue, the type “lvalue reference to A” is used in place of A for type deduction. Thus, in the case where P is const T&& (which is not a forwarding reference), it is transformed to const T and whether or not the argument is an lvalue doesn't affect the type deduction, since value category is not part of the argument's type. Instead, the deduction process simply attempts to find T such that const T is the same type as the argument (possibly with additional cv-qualification). In the case of i and j, this means T is deduced as int and the argument type is const int&&. But in the special forwarding reference case, while P is still transformed from T&& to T, the fact that it was originally a forwarding reference results in the replacement of an argument type by the corresponding lvalue reference type (if the argument is an lvalue). Thus, in the case of i, the transformed argument type is int&, and in the case of j, it is const int&. In both cases, T is deduced in such a way as to make it identical to the transformed argument type, which means T is deduced as a reference type.
69,948,322
69,969,005
Visual Studio 2019: Auto Indent
Apologies for the triviality of this problem - I can't seem to find an answer anywhere. Suppose I have the following block: int plus(int x, int y) { int z = x + y;% Cursor is here } After pressing return, I want the cursor to land here: int plus(int x, int y) { int z = x + y; % Cursor is here } But right now, it's landing here: int plus(int x, int y) { int z = x + y; % Cursor is here } How can I make the editor auto-indent to the beginning of the previous line?
You can set Tools -> Options -> Text editor -> C/C++-> Tabs -> Indenting:Smart in Visual Studio.
69,948,501
69,948,700
How do I write this pseudocode in C++? Function returns two arrays to two initialized arrays
I am trying to implement a bottom up approach function to the rod cutting problem and I need to use this particular pseudo-code from the CLRS textbook. In it there two functions and one calls the other in this fashion (r,s) = EXTENDED-BOTTOM-UP-CUT-ROD(p,n) Where r and s are two different arrays. The function also returns two arrays. I am currently using C++ and I've tried things such as (r,s)=function(p,n); [r,s]=function(p,n); {r,s}=function(p,n); //return statements follow similar attempts return (r,s); return {r,s}; return [r,s]; All these typically resulted in errors or incorrect outputs. Perhaps I shouldn't be using basic arrays for this implementation?
You can use tuples and "structured binding" in C++17 to return multiple values efficiently as below: #include <tuple> #invlude <vector> std::tuple<std::vector<int>,std::vector<int>> func_that_returns_two_vectors() { std::vector<int> v1 = {1, 2, 3}; std::vector<int> v2 = {4, 5, 6}; return {std::move(v1), std::move(v2)}; } int main() { auto [v1, v2] = func_that_returns_two_vectors(); return 0; } To do something similar pre-C++17 you can use std::tie.
69,949,097
69,960,720
Unable to use CA2CT and CW2T in Visual Studio 2022 when C++20 is specified
I am having a problem trying to use C++20 with Visual Studio 2022: For example: CA2CT CW2T CA2W error C2440: 'initializing': cannot convert from ATL::CA2W to ATL::CStringT<wchar_t,StrTraitMFC<wchar_t,ATL::ChTraitsCRT<wchar_t>>> If I revert to C++17 it is fine. Why is this? Here is an example: CLSID AppCLSID ; if (SUCCEEDED(::CLSIDFromProgID(CT2W(rstrProgID), &AppCLSID) ) ) { LPOLESTR pszName = NULL ; if (SUCCEEDED(::ProgIDFromCLSID(AppCLSID, &pszName) ) ) { CString strAppID = CW2T(pszName); } } Note that rStrProgId could be values like _T("Word.Application"). The above scpecific case the error is: error C2440: 'initializing': cannot convert from ATL::CW2W to ATL::CStringT<wchar_t,StrTraitMFC_DLL<wchar_t,ATL::ChTraitsCRT<wchar_t>>> Other code snippets as examples: Example 2 CString strCalendarName = CA2CT(pName->GetText(), CP_UTF8); (the value of pName->GetText() is const char *). Update Doing what @Inspectable says resolves the one issue. The others (examples) that won't compile are: std::string s1 = CT2A(strNameText); CString strStudent1 = CA2CT(pElement1->GetText(), CP_UTF8); There are other compiling issues but I feel they are outside the scope of this question.
The issue evidently relates to /permissive- compiler option. If c++20 is selected, the compiler forces /permissive- option. /permissive- (Standards conformance) The /permissive- option is implicitly set by the /std:c++latest option starting in Visual Studio 2019 version 16.8, and in version 16.11 by the /std:c++20 option. /permissive- is required for C++20 Modules support. With /permissive- or /std:c++20 enabled, the compiler will not allow CStringA a = CW2A(L"123"); (I think because CW2A/CA2W use a conversion operator to return TCHAR* buffer to CString), so it needs {} initialization CStringA a { CW2A(L"123") }; In this case it makes no difference with or without conformance, as far as I understand. But {} is preferred for initialization since c++11. For example it can check for narrowing conversion, and it's more consistent with other initialization forms: char c = 256;//compiles with warning, narrowing conversion char c {256};//won't compile char c[] = { 1,2 };//ok auto c {256};//compiles, auto -> int c auto c = {256};//std::initializer_list, cout << *c.begin(); foo::foo(int i) : m_int{ i } {};//member initialization list RECT rc{};//set all members to zero
69,949,194
69,951,995
OpenGL 2D Circle - Rotated AABB Collision
I have trouble figuring out a way to detect collision between a circle and a rotated rectangle. My approach was to first rotate the circle and the rectangle by -angle, where angle is the amount of radians the rectangle is rotated. Therefore, the rectangle and the circle are aligned with the axes, so I can perform the basic circle - AABB collision detection. bool CheckCollision(float circleX, float circleY, float radius, float left, float bottom, float width, float height, float angle){ // Rotating the circle and the rectangle with -angle circleX = circleX * cos(-angle) - circleY * sin(-angle); circleY = circleX * sin(-angle) + circleY * cos(-angle); left = left * cos(-angle) - bottom* sin(-angle); bottom = left * sin(-angle) + bottom * cos(-angle); } glm::vec2 center(circleX, circleY); // calculate AABB info (center, half-extents) glm::vec2 aabb_half_extents(width / 2.0f, height / 2.0f); glm::vec2 aabb_center( left + aabb_half_extents.x, bottom + aabb_half_extents.y ); // get difference vector between both centers glm::vec2 difference = center - aabb_center; glm::vec2 clamped = glm::clamp(difference, -aabb_half_extents, aabb_half_extents); // add clamped value to AABB_center and we get the value of box closest to circle glm::vec2 closest = aabb_center + clamped; // retrieve vector between center circle and closest point AABB and check if length <= radius difference = closest - center; return glm::length(difference) < radius;
Let rectangle center is rcx, rcy. Set coordinate origin in this point and rotate circle center about this point (cx, cy are coordinates relative to rectangle center): cx = (circleX - rcx) * cos(-angle) - (circleY - rcy) * sin(-angle); cy = (circleX - rcx) * sin(-angle) + (circleY - rcy) * cos(-angle); Now get squared distance from circle center to rectangle's closest point(zero denotes circle center is inside rectangle): dx = max(Abs(cx) - rect_width / 2, 0) dy = max(Abs(cy) - rect_height / 2, 0) SquaredDistance = dx * dx + dy * dy Then compare it with squared radius
69,950,385
69,950,522
How to solve the VS code error includePath in C++?
In C++ when I run the program it shows the error "no such directory found" and reflects "edit include path" when we right-click on the bulb which is appearing on the header file.
Well, I'm just a beginner. I tried many solutions for this problem but found nothing and finally realized there is this one teeny tiny error. that being, I wrote the wrong extension which was".c", while the extension used for C++ is ".cpp" // and this worked for me.
69,950,551
69,957,000
How to build and use an external library with CMake
I am trying to build a portable sound synthesiser using the cross-platform library portaudio. The library has it's own CMake file to be built with. I think I have managed to build it as part of my project (build finishes with exit code 0) but I can't figure how to actually use it's imports. Any #include I try to use results in cannot open source file. This is my project's CMake file: cmake_minimum_required(VERSION 3.0.0) project(sound-synth VERSION 0.1.0) include(CTest) enable_testing() include(ExternalProject) # first try # ExternalProject_Add(portaudio # GIT_REPOSITORY https://github.com/PortAudio/portaudio.git # ) # second try after using git submodule add https://github.com/PortAudio/portaudio.git external/portaudio add_subdirectory(external/portaudio EXCLUDE_FROM_ALL) file(GLOB_RECURSE SRC_FILES src/*.cpp) add_executable(sound-synth main.cpp ${SRC_FILES}) target_include_directories(sound-synth PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) set(CPACK_PROJECT_NAME ${PROJECT_NAME}) set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) include(CPack) And this is how it looks trying to include header files from the library I am using VSC's CMakeTools and the MSVC compiler.
I had to also link the executable with the library with target_link_libraries(sound-synth PortAudio). Then on windows I had the problem that the .dll was placed in a separate folder from the .exe. So I just added a copy file command and that fixed it.
69,950,658
69,952,705
Setting maximum static alignment in Eigen from CMake
I'm working in a general CMake script that provides a grateful fallback strategy regarding activation of vectorization capabilities while compiling a project with Eigen. Using Eigen 3.4 with C++17 standard and compiled with an updated compiler (ex. gcc > 7), there is no code requirements for the developer to comply regarding static objects alignment. No more EIGEN_MAKE_ALIGNED_OPERATOR_NEW macro and explicit alignment in STL containers (and we cheered hard in our lab for this!). But we have a diverse landscape of projects with diverse compilation setups. We would like to write our code without worrying about alignment while a CMake script detects the architecture+compilation capabilities and deactivates Eigen's unsafe vectorization features for the architecture (even when this means breaking abi-compatibility). Is there a way to retrieve the architecture max alignment size at CMake level, to properly set the EIGEN_MAX_STATIC_ALIGN_BYTES directive?? Maybe a bash script that retrieves the max_align_t? https://en.cppreference.com/w/cpp/types/max_align_t
While fabian idea is great it has one huge drawback - you have to run the executable. Not always can you run the executable. The goal is to get the value of alignof(std::max_align_t) without running anything, only with compilation. And we can do it. As always, learn from the best. From CMake modules inspect files: CMakeCompilerABI.h CMakeCCompilerABI.c CMakeDetermineCompilerABI.cmake. Note how CMakeCompilerABI.h embeds the information into executable, without actually printing it. Take the same approuch. Your source file would look like the following: // determineAlingofMax.cpp #include <cstddef> #define VAL alignof(std::max_align_t) const char info_alingof_max_align_t[] = { 'I', 'N', 'F', 'O', ':', 'a', 'l', 'i', 'n', 'g', 'o', 'f', 'm', 'a', 'x' '[', '0' + ((VAL / 10) % 10), '0' + (VAL % 10), ']', '\0', }; int main(int argc, char *argv[]) { return info_alingof_max_align_t[argc]; } Note how we calculated the alignof and converted it to a string at compile time. Now we have to compile it to an object file - we do not need to run any executable. So we take a look at CMakeDetermineCompilerABI.cmake and write similar: set(BIN "${CMAKE_BINARY_DIR}/determineAlingofMax.bin" try_compile(ALIGNMAX_COMPILED ${CMAKE_BINARY_DIR} SOURCES /path/to/the/determineAlingofMax.cpp CMAKE_FLAGS ${CMAKE_FLAGS} # Ignore unused flags "--no-warn-unused-cli" COMPILE_DEFINITIONS ${COMPILE_DEFINITIONS} COPY_FILE "${BIN}" COPY_FILE_ERROR copy_error OUTPUT_VARIABLE OUTPUT ) if (ALIGNMAX_COMPILED AND not copy_error) file(STRINGS "${BIN}" data REGEX "INFO:alingofmax\\[[^]]*\\]") if (data MATCHES "INFO:alingofmax\\[0*([^]]*)\\]") set(ALINGOFMAX "${CMAKE_MATCH_1}" CACHE INTERNAL "") endif() endif() if (NOT ALINGOFMAX) message(FATAL_ERROR some error here) endif() # and finally, maybe option() set(EIGEN_MAX_STATIC_ALIGN_BYTES ${ALINGOFMAX}) Note how the binary is not executed - only compiled. The string INFO:alignofmax has to be only unique enough, so it does not come anywhere in the executable - I prefer to use UUIDs lately.
69,950,750
69,950,772
How do I avoid checking everything with a different If using for loops?
In C++, how do I avoid walls of ifs using for loops? stackoverflow is requesting more text soo... Code Example: if(masiv[0][0] == 'X'){ masiv[0][0] = '1'; } if(masiv[0][1] == 'X'){ masiv[0][1] = '2'; } if(masiv[0][2] == 'X'){ masiv[0][2] = '3'; } if(masiv[1][0] == 'X'){ masiv[1][0] = '4'; } if(masiv[1][1] == 'X'){ masiv[1][1] = '5'; } if(masiv[1][2] == 'X'){ masiv[1][2] = '6'; } if(masiv[2][0] == 'X'){ masiv[2][0] = '7'; } if(masiv[2][1] == 'X'){ masiv[2][1] = '8'; } if(masiv[2][2] == 'X'){ masiv[2][2] = '9'; }
for (int y = 0; y < 3; ++y) { for (int x = 0; x < 3; ++x) { if (masiv[y][x] == 'X') { masiv[y][x] = '1' + 3 * y + x; } } } Some explanation follows. The following pattern is repeating: if (masiv[...][...] == 'X') { masiv[...][...] = '...'; } Because it is repeating, we put it to the body of the for loop. We need 2 for loops, because the first and the second indexes in masiv[...][...] go over all possible values independently, and each variation is present. We will use a separate loop variable for each index, thus it becomes masiv[y][x]. The lower limit for y is 0 (inclusive) and the upper limit for y is 3 (exclusive), hence the for line looks like: for (int y = 0; y < 3; ++y) {. Similarly for x. We need a different character after the masiv[y][x] =. Since digits are next to each other in the ASCII table (e.g. '5' + 3 == '8'). we use an expression like '1' + ...y... + ...x.... The actual value starts from '1' in the beginning, and it increases by 1 as x increases, and it increases by 3 when y increases. Thus it's '1' + 3 * y + x.
69,950,981
69,951,073
How to check if a member function or free function is for the exact given type(not any of its base)?
A way to check if a member function/free function can be invoked on an object would be to: #include <type_traits> #include <utility> template <class T, class = void> struct HasMember : std::false_type {}; template <class T> struct HasMember<T, std::void_t<decltype(std::declval<T>().Foo())>> : std::true_type {}; template <class T, class = void> struct HasFreeFoo : std::false_type {}; template <class T> struct HasFreeFoo<T, std::void_t<decltype(Foo(std::declval<T>()))>> : std::true_type {}; struct A { void Foo() {} }; struct B : A {}; struct C : B {}; void Foo(const A &) {} int main() { static_assert(HasMember<C>::value, ""); static_assert(HasFreeFoo<C>::value, ""); } But as what the example demonstrates, C is considered to have the member Foo since A has implemented Foo, C is considered to have the free function Foo implemented since Foo accept const A &. What I want to achieve is to have HasMember<A>::value == true && HasMember<C>::value == false. HasFreeFoo<A>::value == true && HasFreeFoo<C>::value == false. Any help is welcome, thanks. Background: I am implementing a ser/des tool, user can choose to either implement a member function or a free function to specify how should a type get ser/des. And I need to check if such member function / free function are implemented (not inherited from its base) exactly for the given type .
The implementation of HasMember and HasFreeFoo is reasonable since C can indeed obtain Foo() through inheritance. What you need is to implement another trait to choose whether to invoke through the member function or the free function. For example: template <class T, class = void> struct UseMemberFoo : std::false_type {}; template <class T> struct UseMemberFoo<T, std::enable_if_t<HasMember<T>::value && !HasFreeFoo<T>::value>> : std::true_type { }; template<class T> void Foo(const T&) = delete; template <class T, class = void> struct UseFreeFoo : std::false_type {}; template <class T> struct UseFreeFoo<T, std::enable_if_t<HasMember<T>::value && HasFreeFoo<T>::value>> : std::true_type { }; When T only has member Foo(), then invoke it through the member function. When the user inherits the base class which has member Foo() and provides the free function for the derived class, then invoke it through the free function. Demo.
69,951,144
69,951,246
Why doesn't std::tie work with const class methods?
#include <string> #include <tuple> #include <stdexcept> using namespace std; class Date { public: Date() {}; Date(int new_year, int new_month, int new_day) { year = new_year; if ((new_month < 1) || (new_month > 12)) { throw runtime_error("Month value is invalid: " + to_string(new_month)); } month = new_month; if ((new_day < 1) || (new_day > 31)) { throw runtime_error("Day value is invalid: " + to_string(new_day)); } day = new_day; } int GetYear() const { return year; } int GetMonth() const { return month; } int GetDay() const { return day; } private: int year; int month; int day; }; bool operator < (const Date &lhs, const Date &rhs) { auto lhs = tie(lhs.GetYear(), lhs.GetMonth(), lhs.GetDay()); auto rhs = tie(rhs.GetYear(), rhs.GetMonth(), rhs.GetDay()); return lhs < rhs; } I'm trying to create a class for storing the date (year, month, day). In order to use this class in a map, I want to overload the comparison operator. Unfortunately, the code above does not work. The compiler gives me an error error: cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'| The error apparently occurs in tie function. Once I change it to make_tuple everything compiles and works. I also checked that if I declared variables year, month and day as public I could write something like auto lhs = tie(lhs.year, lhs.month, lhs.day); and this would also work. I don't understand why. Does anyone have ideas?
Your member functions return copy of the members(aka temprory rvalue), and std::tie has argument list, which try to bind by non-cost lvalue ref. template< class... Types > constexpr std::tuple<Types&...> tie( Types&... args ) noexcept; // ^^^^^^^^^^^^^^^^ This is simply not possible as per standard, hence the error! The std::make_tuple on the other hand has forwarding reference. Therefore, no issues. template< class... Types > std::tuple<VTypes...> make_tuple( Types&&... args ); // ^^^^^^^^^^^^^^^^ When the members are public, they became lvalues. I would suggest, make the operator< friend of the class instead. class Date { public: // .... other code friend bool operator<(const Date& lhs, const Date& rhs) noexcept { return std::tie(lhs.year, lhs.month, lhs.day) < std::tie(rhs.year, rhs.month, rhs.day); } private: int year; int month; int day; };
69,951,242
69,951,393
Diamond Problem C++: Derived class of diamond calls default constructor
So as part of the public API of my program I expose class D, such that the user inherits from class D to create their own classes. However class D is the tip of the deadly diamond and I have run into an issue where the user's classes are calling the default constructor of class A, instead of the parametrized constructor as desired. A / \ B C \ / D | E or F In the following code, class E is a clean API however calls the wrong A constructor. Class F works as intended, however the user has to add A's parameterised constructor, which is ugly because that class is an internal class. Is there a way to have class E work as intended? Why is this happening? #include<iostream> using namespace std; class A { public: A(int x) { cout << "A::A(int ) called" << endl; } A() { cout << "A::A() called" << endl; } }; class B : virtual public A { public: B(int x): A(x) { cout<<"B::B(int ) called"<< endl; } }; class C : virtual public A { public: C(int x): A(x) { cout<<"C::C(int ) called"<< endl; } }; class D : public B, public C { public: D(int x): A(x), B(x), C(x) { cout<<"D::D(int ) called"<< endl; } }; class E : public D { public: E(int x): D(x) { cout<<"E::E(int ) called"<<endl; } }; class F : public D { public: F(int x): D(x), A(x) { cout<<"F::F(int ) called"<<endl; } }; int main() { D d(0); cout<<endl; E e(1); cout<<endl; F f(2); } Output: A::A(int ) called B::B(int ) called C::C(int ) called D::D(int ) called A::A() called B::B(int ) called C::C(int ) called D::D(int ) called E::E(int ) called A::A(int ) called B::B(int ) called C::C(int ) called D::D(int ) called F::F(int ) called
When constructing a class that has any virtual bases, initializers that name a virtual base class are only called for the most derived class. If your class has any virtual base classes, and you want to use the non-default constructor of that virtual base, then you must specify that constructor in the derived class. 1 "All virtual base subobjects are initialized before any non-virtual base subobject, so only the most derived class calls the constructors of the virtual bases in its member initializer list: ..." 2 "The initializers where class-or-identifier names a virtual base class are ignored during construction of any class that is not the most derived class of the object that's being constructed." This topic is relatively new to me, so I hope anybody with more experience will point out any nuance I missed.
69,951,402
69,951,522
How do I get weighted sum of 2 vectors in C++?
I saw the post here to sum 2 vectors. I wanted to do a weighted sum. std::vector<int> a;//looks like this: 2,0,1,5,0 std::vector<int> b;//looks like this: 0,0,1,3,5 I want to do a * 0.25 + b * 0.75 and store in some vector. I saw this function std::transform but wanted to know how do I write a custom operation for that.
Version 1: Using std::transform and a lambda #include <iostream> #include <vector> #include<algorithm> int main() { std::vector<int> a{2,0,1,5,0}; std::vector<int> b{0,0,1,3,5}; //create a new vector that will contain the resulting values std::vector<double> result(a.size()); std::transform (a.begin(), a.end(), b.begin(), result.begin(), [](int p, int q) -> double { return (p * 0.25) + (q * 0.75); }); for(double elem: result) { std::cout<<elem<<std::endl; } return 0; } Version 2: Using a free function #include <iostream> #include <vector> #include<algorithm> double weightedSum(int p, int q) { return (p * 0.25) + (q * 0.75); } int main() { std::vector<int> a{2,0,1,5,0}; std::vector<int> b{0,0,1,3,5}; //create a new vector that will contain the resulting values std::vector<double> result(a.size()); std::transform (a.begin(), a.end(), b.begin(), result.begin(), weightedSum); for(double elem: result) { std::cout<<elem<<std::endl; } return 0; } Version 3: Passing the weights as arguments using std::bind #include <iostream> #include <vector> #include<algorithm> #include <functional> using namespace std::placeholders; double weightedSum(int p, int q, double weightA, double weightB) { return (p * weightA) + (q * weightB); } int main() { std::vector<int> a{2,0,1,5,0}; std::vector<int> b{0,0,1,3,5}; //create a new vector that will contain the resulting values std::vector<double> result(a.size()); std::transform (a.begin(), a.end(), b.begin(), result.begin(), std::bind(weightedSum, _1, _2, 0.25, 0.75)); for(double elem: result) { std::cout<<elem<<std::endl; } return 0; }
69,951,456
69,952,404
std::this_thread::sleep_for doesn't exist - Windows 10 g++
I am currently running a test program which executes perfectly well online (replit.com), but when I run it locally (on Windows 10 with gcc and g++) I get an error: test.cpp: In function 'int main()': test.cpp:18:8: error: 'std::this_thread' has not been declared std::this_thread::sleep_for(std::chrono::milliseconds(time)); This is my program: #include <iostream> #include <thread> #include <chrono> #include <random> #include <string> int randomInt (int MIN, int MAX) { std::random_device rd; std::default_random_engine eng(rd()); std::uniform_int_distribution<int> distr(MIN, MAX); return distr(eng); } int main() { int loop = 20; for (int i = 0; i < loop; i++) { int time = randomInt(10, 100); std::this_thread::sleep_for(std::chrono::milliseconds(time)); } return 0; } Why does this happen?
I went back to replit.com to see what they were doing to compile the program. Apparently they used the -pthreads switch: g++ -pthread -std=c++17 -o main main.cpp Which now works for me.
69,952,077
69,953,068
MSCV give an error about "unrecognized source file type..." although I didn't specify any arguments
I'm having a problem about MSVC. When I try run Developer command prompt and type cl, it give me this error: Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30137 for x86 Copyright (C) Microsoft Corporation. All rights reserved. cl : Command line warning D9024 : unrecognized source file type 'C:\Program', object file assumed cl : Command line warning D9024 : unrecognized source file type 'Files', object file assumed cl : Command line warning D9024 : unrecognized source file type '(x86)\Microsoft', object file assumed cl : Command line warning D9024 : unrecognized source file type 'Visual', object file assumed cl : Command line warning D9024 : unrecognized source file type 'Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\Hostx86\x86\cl.exe', object file assumed Microsoft (R) Incremental Linker Version 14.29.30137.0 Copyright (C) Microsoft Corporation. All rights reserved. /out:Program.exe C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\Hostx86\x86\cl.exe LINK : fatal error LNK1104: cannot open file 'Program.exe' I'm not sure what happening. I try reinstalling Visual Studio and repairing it yet still not working. I try to do some research to find the solutions, none found.
Check if you have a user or system environment variable called either CL or _CL_ defined. Assuming Windows 10, go to Start → Settings → System → About → click on the Advanced system settings link, then in the System Properties dialog, on the Advanced tab, click the Environment Variables… button to see and check in both lists there. As documented by Microsoft on CL environment variables, defining such variables will interfere with the CL tool by prepending or appending the specified arguments to the command line. Sometimes, setting a CL or _CL_ variable before invoking MSBuild is useful for injecting preprocessor macros (using the /D option) to alter some aspect of the compilation, for example. Normally, there should be no such variables in the environment. Perhaps you have one of those variables globally set to the path of cl.exe, this is wrong. So, just delete the variable(s).
69,952,644
69,952,694
printing content of an array into .txt file
the ifstream part(reading .csv file into array) works perfectly but the ofstream part(printing array into .txt file) gives error. got error no match for 'operator<<' #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <iomanip> using namespace std; int main() { ifstream in("test.csv"); string line, field; vector <vector <string>> array; vector <string> v; while (getline(in, line)) { v.clear(); stringstream ss(line); while(getline(ss,field,',')) { v.push_back(field); } array.push_back(v); } ofstream myfile("test1.txt"); myfile<<array; myfile.close(); error message: error: no match for 'operator<<' (operand types are 'std::ofstream' {aka 'std::basic_ofstream<char>'} and 'std::vector<std::vector<std::__cxx11::basic_string<char> > >')
There is no operator overloaded for the std::vector<std::vector<std::string>> in the std::ofstream, so you can't do that. One way you could do this is: std::ofstream myfile("test1.txt"); if (myfile) { //https://www.cplusplus.com/reference/ostream/ostream/write/ for (auto& elem : array) { for (auto& str : elem) { myfile.write(str.data(), str.size()); } } myfile.close(); } I would prefer JSON, for serializing this type of stuff.
69,952,780
69,954,585
Regex to replace single occurrence of character in C++ with another character
I am trying to replace a single occurrence of a character '1' in a String with a different character. This same character can occur multiple times in the String which I am not interested in. For example, in the below string I want to replace the single occurrence of 1 with 2. input:-0001011101 output:-0002011102 I tried the below regex but it is giving be wrong results regex b1("(1){1}"); S1=regex_replace( S, b1, "2"); Any help would be greatly appreciated.
If you used boost::regex, Boost regex library, you could simply use a lookaround-based solution like (?<!1)1(?!1) And then replace with 2. With std::regex, you cannot use lookbehinds, but you can use a regex that captures either start of string or any one char other than your char, then matches your char, and then makes sure your char does not occur immediately on the right. Then, you may replace with $01 backreference to Group 1 (the 0 is necessary since the $12 replacement pattern would be parsed as Group 12, an empty string here since there is no Group 12 in the match structure): regex reg("([^1]|^)1(?!1)"); S1=std::regex_replace(S, regex, "$012"); See the C++ demo online: #include <iostream> #include <regex> int main() { std::string S = "-0001011101"; std::regex reg("([^1]|^)1(?!1)"); std::cout << std::regex_replace(S, reg, "$012") << std::endl; return 0; } // => -0002011102 Details: ([^1]|^) - Capturing group 1: any char other than 1 ([^...] is a negated character class) or start of string (^ is a start of string anchor) 1 - a 1 char (?!1) - a negative lookahead that fails the match if there is a 1 char immediately to the right of the current location.
69,952,790
69,952,884
why i can't pass a char pointer to lambda. C++ Primer ex13.44
I am writing a simplified version of std::string. When i'm writing the free function, i use the for_each function like this: void String::free() { std::for_each(element, end, [this](char *c){ alloc.destroy(c); }); alloc.deallocate(element, end-element); } This function will destory the char memory, and delete the memory space allocated by allocator. But it will be error when i compile it. In file included from /usr/include/c++/9/algorithm:62, from 13_44_String.cpp:2: /usr/include/c++/9/bits/stl_algo.h: In instantiation of ‘_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = char*; _Funct = String::free()::<lambda(char*)>]’: 13_44_String.cpp:20:69: required from here /usr/include/c++/9/bits/stl_algo.h:3876:5: error: no match for call to ‘(String::free()::<lambda(char*)>) (char&)’ 3876 | __f(*__first); | ~~~^~~~~~~~~~ 13_44_String.cpp:20:33: note: candidate: ‘String::free()::<lambda(char*)>’ <near match> 20 | std::for_each(element, end, [this](char *c){ alloc.destroy(c); }); | ^ 13_44_String.cpp:20:33: note: conversion of argument 1 would be ill-formed: In file included from /usr/include/c++/9/algorithm:62, from 13_44_String.cpp:2: /usr/include/c++/9/bits/stl_algo.h:3876:5: error: invalid conversion from ‘char’ to ‘char*’ [-fpermissive] 3876 | __f(*__first); | ~~~^~~~~~~~~~ | | | char The right answer is change char * to char & like this: void String::free() { std::for_each(element, end, [this](char &c){ alloc.destroy(&c); }); alloc.deallocate(element, end-element); } I do not know why i can't pass a char pointer to a lambda. Why i must use the &.
From std::for_each documentation: template< class InputIt, class UnaryFunction > UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f ); Applies the given function object f to the result of dereferencing every iterator in the range [first, last), in order. Note the emphasis on result of dereferencing in the above quote. Now lets apply this quote to your 1st code snippet. In your case: f is equivalent to the lambda that you supplied result of dereferencing the iterator is char So the parameter should be a char type. But you're supplying/specifying a char* so you get the mentioned error. Now in your 2nd code snippet, you fixed this by specifying the parameter type in the lambda to be char& and so the code works.
69,952,992
69,953,057
Subtract each elements of an array consecutively
I have an array and I want to subtract each of the elements consecutively, ex: {1,2,3,4,5}, and it will result to -13 which is by 1-2-3-4-5. But I don't declare or make those numbers fixed as they're taken from the input (user). I only make it like, int array[100] to declare the size. Then, to get the inputs, I use the for loop and insert them to the array. Let's say first input is 10, then array[0] must be 10 and so on. The problem is, how do I subtract them? I have two options: The first element of the array (array[0]) will subtract the next element (array[1]) right after the user input the second element, and the result (let's say it's int x) will subtract the next element (array[2]) after the user input it and so on. I'll have the user input all the numbers first, then subtract them one by one automatically using a loop (or any idea?) *These elements thing refer to the numbers the user input. Question: How do you solve this problem? (This program will let the user input for as much as they want until they type count. Frankly speaking, yeah I know it's quite absurd to see one typing words in the middle of inputting numbers, but in this case, just how can you do it?) Thanks. Let's see my code below of how I insert the user input into the array. string input[100]; int arrayInput[100]; int x = 0; for (int i = 0; i >= 0; i++) //which this will run until the user input 'count' { cout << "Number " << i+1 << ": "; cin >> input[i]; arrayInput[i] = atoi(input[i].c_str()); ... //code to subtract them, and final answer will be in int x ... if (input[i] == "count") { cout << "Result: " << x << endl; } }
You can/should use a dynamic sized container like std::vector as shown below: #include <iostream> #include <vector> int main() { int n = 0; //ask user how many input he/she wants to give std::cout << "How many elements do you want to enter: "; std::cin >> n; std::vector<int> vec(n); //create a vector of size n int resultOfSubtraction = 0; //take input from user for(int i = 0 ; i < n ; ++i) { std::cin >> vec.at(i); if(i != 0) { resultOfSubtraction-= vec.at(i); } else { resultOfSubtraction = vec.at(i); } } std::cout<<"result is: "<<resultOfSubtraction<<std::endl; return 0; } Execute the program here. If you want a string to end the loop then you can use: #include <iostream> #include <vector> #include <sstream> int main() { std::vector<int> vec; int resultOfSubtraction = 0, i = 0; std::string endLoopString = "count"; std::string inputString; int number = 0; //take input from user while((std::getline(std::cin, inputString)) && (inputString!=endLoopString)) { std::istringstream ss(inputString); if(ss >> number) { vec.push_back(number); if(i == 0) { resultOfSubtraction = number; } else { resultOfSubtraction-= number; } ++i; } } std::cout<<"result is: "<<resultOfSubtraction<<std::endl; return 0; }
69,953,378
69,953,486
Figuring out why capturing by reference in a nested lambda produces a weird result
When the outer variable x is captured by value return [=](int y){ return x * y; }; foo(2)(3) produces 6. However if I capture x by reference return [&](int y){ return x * y; }; foo(2)(3) produces 9. Minimal Code #include <iostream> #include <functional> int main() { using namespace std; function<function<int(int)>(int)> foo = [](int x) { return [&](int y) { return x * y; }; }; cout << foo(2)(3); return 0; } Question I cannot figure out why this happens, can you?
x is local to the outer function, so it's destroyed as soon as that function returns. Consider a simpler example. #include <iostream> #include <functional> int& foo(int x) { return x; } int main() { using namespace std; int& b = foo(5); return 0; } Here it's easier to see that b is a dangling reference. Next we go ahead and instead of returning the reference directly, we return a lambda that captures the variable by reference. #include <iostream> #include <functional> auto foo(int x) { return [&x]() {return x;}; } int main() { using namespace std; auto b = foo(5); return 0; } The problem still remains. Once the lambda is returned, x has already gone out of scope and is no longer alive. But the lambda holds a (dangling) reference to it.
69,953,667
69,954,097
Why is array of characters(char type) working with unicode characters (c++)?
When i wrte this code : using namespace std; int main(){ char x[] = "γεια σας"; cout << x; return 0; } I noticed that compiler gave me output which i excepted γεια σας Although the type of array is char, That is, it should just accept ASCII characters. So why compiler didn't give error?
Here's some code showing what C++ really does: #include <iostream> #include <iomanip> using namespace std; int main(){ char x[] = "γεια σας"; cout << x << endl; auto len = strlen(x); cout << "Length (in bytes): " << len << endl; for (int i = 0; i < len; i++) cout << "0x" << setw(2) << hex << static_cast<int>(static_cast<unsigned char>(x[i])) << ' '; cout << endl; return 0; } The output is: γεια σας Length (in bytes): 15 0xce 0xb3 0xce 0xb5 0xce 0xb9 0xce 0xb1 0x20 0xcf 0x83 0xce 0xb1 0xcf 0x82 So the string takes up 15 bytes and is encoded as UTF-8. UTF-8 is a Unicode encoding using between 1 and 4 bytes per character (in the sense of the smallest unit you can select with the text cursor). UTF-8 can be saved in a char array. Even though it's called char, it basically corresponds to a byte and not what we typically think of as a character.
69,953,687
69,954,347
C++ - Calculate the millisecond from ptime in total seconds
How do i calculate the millisecond difference from the following Ptime ,I am using boost::ptime I'm trying to calculate the time_duration in milliseconds to find the difference. i get value like 999975 but expected value is 975 ptime PreviousgpsTime = Mon Jun 28 17:07:10.054 2021 ptime NextgpsTime = Mon Jun 28 17:07:11.025 2021 double totalDiff = (NextgpsTime-PreviousgpsTime).total_milliseconds(); How to fix this and get the actual time duration.
Live On Coliru: #include <boost/date_time/posix_time/posix_time.hpp> int main() { using namespace boost::posix_time; ptime PreviousgpsTime = time_from_string("2021-Jun-28 17:07:10.054"); ptime NextgpsTime = time_from_string("2021-Jun-28 17:07:11.025"); long totalDiff = (NextgpsTime - PreviousgpsTime).total_milliseconds(); std::cout << "From " << PreviousgpsTime << " to " << NextgpsTime << " is " << totalDiff << "ms\n"; } Prints From 2021-Jun-28 17:07:10.054000 to 2021-Jun-28 17:07:11.025000 is 971ms
69,954,329
69,965,184
How do you save a setquery count to a string in Qt
QSqlQueryModel * model=new QSqlQueryModel (); int i,id; QString count; model->setQuery("SET '"+count+"' =(SELECT COUNT(*) from COLLABORATEUR)"); qInfo() << count; i tried this code but count is still clear i always get "" i tried it like this too: model->setQuery("SELECT '"+count+"'=COUNT(*) from COLLABORATEUR"); and like this : model->setQuery("SELECT @count=COUNT(*) from COLLABORATEUR"); but count is still empty
If you just need to count the number of records, then use directly rowCount(). QString count = QString::number(model->rowCount()); qInfo() << count;
69,954,361
69,954,489
Game Engine: Class parameter
I am doing university work for a game engine and we needed to do an agnostic code. They told us to do the rest on our own and I am on the right track however, when I try and pass the parameters for the function it says it doesn't pass for the arguments? This I believe is due to the class parameter that I have on there. Am I being an idiot or ? Error: (without Buffer Layout) function arguments don't match. Or with the code you can see it says "Expected an expression" Please help! Vertex Buffer /* \file OpenGLVertexBuffer.cpp */ #include "engine_pch.h" #include <glad/glad.h> #include "include/independent/platform/OpenGL/OpenGLVertexBuffer.h" namespace Engine { void BufferLayout::addElement(BufferElement element) { m_elements.push_back(element); calcStrideAndOffset(); } void BufferLayout::calcStrideAndOffset() { uint32_t l_offset = 0; for (auto& element : m_elements) { element.m_offset = l_offset; l_offset += element.m_size; } m_stride = l_offset; } OpenGLVertexBuffer::OpenGLVertexBuffer(void * vertices, uint32_t size, BufferLayout layout) : m_layout(layout) { glCreateBuffers(1, &m_OpenGL_ID); glBindBuffer(GL_ARRAY_BUFFER, m_OpenGL_ID); glBufferData(GL_ARRAY_BUFFER, size, vertices, GL_DYNAMIC_DRAW); } OpenGLVertexBuffer::~OpenGLVertexBuffer() { glDeleteBuffers(1, &m_OpenGL_ID); } void OpenGLVertexBuffer::edit(void * vertices, uint32_t size, uint32_t offset) { glBindBuffer(GL_ARRAY_BUFFER, m_OpenGL_ID); glBufferSubData(GL_ARRAY_BUFFER, offset, size, vertices); } } Rendering API /* \file renderAPI.cpp */ #include "engine_pch.h" #include "rendering/RenderAPI.h" #include "rendering/indexBuffer.h" #include "rendering/vertexBuffer.h" #include "platform/OpenGL/OpenGLIndexBuffer.h" #include "platform/OpenGL/OpenGLVertexBuffer.h" #include "systems/log.h" namespace Engine { RenderAPI::API Engine::RenderAPI::s_API = RenderAPI::API::OpenGL; IndexBuffer * IndexBuffer::create(uint32_t * indices, uint32_t count) { switch (RenderAPI::getAPI()) { case RenderAPI::API::None: Log::error("No supported Rendering API"); case RenderAPI::API::OpenGL: return new OpenGLIndexBuffer(indices, count); case RenderAPI::API::Direct3D: Log::error("Direct3D not currently Supported!"); case RenderAPI::API::Vulkan: Log::error("Vulkan not currently Supported!"); } } VertexBuffer * VertexBuffer::edit(void* vertices, uint32_t size, uint32_t offset) { switch (RenderAPI::getAPI()) { case RenderAPI::API::None: Log::error("No Supported Rendering API"); case RenderAPI::API::OpenGL: //return new OpenGLVertexBuffer(vertices, sizeof(size), offset); new OpenGLVertexBuffer(vertices, size, <BufferLayout> offset); } } }
The call to "new OpenGLVertexBuffer" expects three arguments a void* an uint32_t a BufferLayout You pass vertices, a void* (okay) sizeof(size) - wrong. It calculates the size of the variable(!) size, which is 4 (uint32 is always 32 bits/4 bytes). So you pass the constant 4 as the second parameter. Not what you want. offset - wrong again. The third parameter is expected to be of type BufferLayout. You are trying to pass a uint32_t, where you should be passing a BufferLayout. In general you need to read up on types (why is uint32_t not a BufferLayout), functions (parameters), constructors. Also you are missing break statements in your switch. Study the switch statement to see what I mean. And you are using pointers (return new something). If they teach you that in university then the course you are taking is very outdated. As a beginner you should NEVER have to use pointers, NEVER work with new. You could use the C++ standard ways of std::shared_ptr<VertexBuffer> instead, using std::make_shared... rather than new. The problem with pointers is that they are just too easily mishandled. You will forget to call delete in the proper place(s), which will lead to memory leaks. Or you will call delete in the wrong places, which will lead to 'use after free' or 'calling delete for a deleted pointer'. shared_ptr and similar classes take off the burden and will do the work for you. The need for pointers has been greatly diminished in modern C++. Finally: When you post a question, please include a: the exact compiler error b: the exact location, where this error occurs. You could for example include a // ERROR MESSAGE HERE comment in your example code. Both points will make it much more likely that someone answers your questions.
69,954,723
69,955,692
Remove focus from SAVE button in OPENFILENAME win32?
Problem: If the user holds the "enter" keyboard button and opens OPENFILENAME Save As Dialog, it will automatically save the file - dialog only blinks. Desired result: The user holds the "enter" keyboard button, opens OPENFILENAME Save As Dialog, nothing happens. He needs to click on the Save button or click again the "enter" keyboard button to save a file. My current code: OPENFILENAME ofn; TCHAR szFile[260] = { 't','e','s','t'}; // example filename // Initialize OPENFILENAME ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hWnd; ofn.lpstrFile = szFile; ofn.nMaxFile = sizeof(szFile); //Files like: (ALL - *.*), (Text - .TXT) ofn.lpstrFilter = _T("All\0*.*\0Text\0*.TXT\0"); ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = NULL; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; if (GetSaveFileName(&ofn) == TRUE) { // file saved } Possible solution: When ofn.lpstrFile is empty do nothing; Can't save file when there is no filename When ofn.lpstrFile has suggested filename then turn off focus on "Save" button or somehow ignore button enter holding. I was trying to do that but failed, I am a beginner in CPP :( Thanks for help
The easy solution to prevent data loss is to add the OFN_OVERWRITEPROMPT flag. This does not prevent the issue from happening if the suggested name does not already exist as a file. To actually interact with the dialog you need OFN_ENABLEHOOK and a hook function. When you receive WM_NOTIFY, you can handle CDN_FILEOK to block the suggested name if not enough time has passed or maybe it is possible to change the focus in CDN_INITDONE. Either way, you have to be mindful of the fact that you are changing how a common dialog works and this might anger some users. Here is one way to do it. The actual delay to return the dialog to normal is something you have to decide for yourself. const int btnid = 1337; void CALLBACK resetsavedlgdefpush(HWND hWnd, UINT Msg, UINT_PTR idEvent, DWORD Time) { KillTimer(hWnd, idEvent); HWND hDlg = GetParent(hWnd); UINT id = LOWORD(SendMessage(hDlg, DM_GETDEFID, 0, 0)); if (id == btnid) { SendMessage(hDlg, DM_SETDEFID, IDOK, 0); } } UINT_PTR CALLBACK mysavehook(HWND hWndInner, UINT Msg, WPARAM wParam, LPARAM lParam) { if (Msg == WM_NOTIFY) { OFNOTIFY*pOFN = (OFNOTIFY*) lParam; if (pOFN->hdr.code == CDN_INITDONE) { HWND hDlg = GetParent(hWndInner); CreateWindowEx(0, TEXT("BUTTON"), 0, BS_DEFPUSHBUTTON|BS_TEXT|WS_CHILD|WS_VISIBLE, 0, 0, 0, 0, hWndInner, (HMENU) btnid, 0, 0); SendMessage(hDlg, DM_SETDEFID, btnid, 0); PostMessage(hDlg, DM_SETDEFID, btnid, 0); int keydelay = 0; SystemParametersInfo(SPI_GETKEYBOARDDELAY, 0, &keydelay, 0); SetTimer(hWndInner, 0, (250 * ++keydelay) * 5, resetsavedlgdefpush); } } return 0; } ... ofn.Flags = OFN_PATHMUSTEXIST|OFN_EXPLORER|OFN_OVERWRITEPROMPT|OFN_ENABLESIZING|OFN_ENABLEHOOK; ofn.lpfnHook = mysavehook; MessageBox(ofn.hwndOwner, TEXT("Hold enter to test..."), 0, 0); if (GetSaveFileName(&ofn) == TRUE) ...