question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
73,865,784
73,866,781
Limiting the scope of a temporary variable
Without resorting to the heap, I would like a temporary variable to pass out of scope, freeing its storage on the stack. However, I can think of no neat way to achieve the desired effect in a case like this: #include <cstdlib> #include <iostream> int main() { const int numerator {14}, denominator {3}; // ... // The desired scope begins here. const std::div_t quotient_and_remainder {std::div(numerator, denominator)}; const int x_lo { quotient_and_remainder.quot }; const int x_hi { quotient_and_remainder.quot + (quotient_and_remainder.rem ? 1 : 0) }; // The desired scope ends here. // The quotient_and_remainder should pass out of scope. // ... std::cout << "The quotient " << numerator << "/" << denominator << " is at least " << x_lo << " and is not more than " << x_hi << "." << "\n"; return 0; } At the low machine level, one desires the following. Storage is first reserved on the stack for x_lo and x_hi. The quotient_and_remainder is then pushed temporarily onto the stack. The quotient_and_remainder is used to calculate values which are written into x_lo and x_hi. Having done its duty, the quotient_and_remainder is popped off the stack. At the high programming level, one desires the following. The compiler enforces that x_lo and x_hi remain constant. The name quotient_and_remainder does not clutter the function's entire local namespace. At both levels, one would like to avoid wasting memory and runtime. (To waste compilation time is okay.) In my actual program—which is too long to post here—the values of numerator and denominator are unknown at compile time, so constexpr cannot be used. Ordinarily, I can think of various sound ways to achieve such effects using, for example, extra braces or maybe an anonymous lambda; but this time, I'm stumped. (One should prefer to solve the problem without anti-idiomatic shenanigans like const_cast. However, if shenanigans were confined to a small part of the program to avert maintainabilty problems, then shenanigans might be acceptable if there existed no better choice.)
In C++17, you can use a function and a structured binding declaration: auto x_lo_x_hi = [](int numerator, int denominator) { std::div_t quotient_and_remainder {std::div(numerator, denominator)}; return std::pair{ quotient_and_remainder.quot, quotient_and_remainder.quot + (quotient_and_remainder.rem ? 1 : 0) }; }; const auto [x_lo, x_hi] = x_lo_x_hi(numerator, denominator); Demo x_lo_x_hi doesn't have to be a local lambda. It could be some function declared elsewhere or it could even be an IIFE (an anonymous lambda that you call immediately on the same line). That said, this only serves to remove the name quotient_and_remainder from the local scope. Like MSalters said in a comment, any decent compiler will optimize that variable away in your original code. And even if it didn't, removing one variable from the stack will not improve the runtime, and if you have stack memory problems, the actual issue is somewhere else.
73,867,157
73,867,339
The AVX intrinsic _mm256_rsqrt_ps has much greater relative error than it should have according to the intrinsics guide
The Intel Intrinsics Guide says that the intrinsic _mm256_rsqrt_ps has a relative error of at most 1.5*2^-12. But, when I compare the result of _mm256_rsqrt_ps to a standard C++ calculation of the inverse of the square root (1.0 / sqrt(x)), I get a relative error much greater than 1.5*2^-12. I used the following program to test this: #include <immintrin.h> #include <iostream> #include <math.h> void test(float x) { float resP = _mm256_cvtss_f32(_mm256_rsqrt_ps(_mm256_set1_ps(x))); float res = 1.0 / sqrt(x); float relErr = fabs(resP - res) / res; std::cout << "x = " << x << std::endl; std::cout << "resP = " << resP << std::endl; std::cout << "res = " << res << std::endl; std::cout << "relErr = " << relErr << std::endl; } int main() { test(1e30); test(1e-30); test(1e17); test(1e-17); } It outputs the following: x = 1e+30 resP = 1.00007e-15 res = 1e-15 relErr = 6.80803e-05 x = 1e-30 resP = 9.99868e+14 res = 1e+15 relErr = 0.0001316 x = 1e+17 resP = 3.16186e-09 res = 3.16228e-09 relErr = 0.000132569 x = 1e-17 resP = 3.16277e+08 res = 3.16228e+08 relErr = 0.000154825 As you can see, the relative error is significantly greater than 1.5*2^-12. The instruction _mm256_rcp_ps also seems to have a much greater relative error than the intrinsics guide says it has. Am I doing something wrong? Am I misunderstanding the intrinsics guide? Or is the intrinsics guide wrong?
Your relative error is in the bound. 1.5*2^-12 = 0.000366 It's just powers of 2 not powers of 10. Also is does not claim to have this relative error in comparison to the single precision 1/sqrt(x) but to the exact result.
73,868,536
73,868,629
I don't understand the problem that the error want to tell me. i copied the error message
#include <iostream>; using namespace std; int main() { int total_of_seconds; cout << "please inter the total of seconds \n"; cin >> total_of_seconds ; int seconds_per_day = 24* 60 *60 ; int seconds_per_hours = 60 * 60 ; int seconds_per_minutes= 60 ; int number_of_days = floor (total_of_seconds/seconds_per_day) ; int s = total_of_seconds % seconds_per_day ; int number_of_hours= floor (s/seconds_per_hours ) ; int s %= seconds_per_hours; int number_of_minutes= floor (s/seconds_per_minutes) ; int s %= seconds_per_minutes; int number_of_seconds = s; cout << number_of_days <<":" << number_of_hours <<":" << number_of_minutes<< ":" << number_of_seconds<<endl ; return 0; } /tmp/uGTkaIpa1f.cpp:11:22: error: 'floor' was not declared in this scope 11 | int number_of_days = floor (total_of_seconds/seconds_per_day) ; | ^~~~~ /tmp/uGTkaIpa1f.cpp:14:7: error: expected initializer before '%=' token 14 | int s %= seconds_per_hours; | ^~
You have declared your variable at int s = total_of_seconds % seconds_per_day ; and you're trying to re-declare it at int s %= seconds_per_hours; remove the int declaration P.S. include the cmath for using floor
73,868,751
73,869,825
Make object searchable with two different keys
Given a class with two keys: class A { int key1; int key2; byte x[]; // large array } If multiple objects of class A are instantiated and I want to sort them by key1, I can insert them into an std::set. But if I want to sort these objects both by key1 and by key2, how would I do that? I could create two sets where one set sorts by key1 and the other set sorts by key2, but that doubles the amount of memory used. How can I avoid this? Edit 1: As far as I know, when an object is inserted into a set, the object is copied. So if I create two sets (one sorted by key1 and one sorted by key2), that means two versions of the object will exist: one in set1 and one in set2. This means that member x also exists twice, which unnecessarily doubles the amount of memory used. Edit 2: To give a more specific example: given the class Person. class Person { std::string name; std::string address; // other fields } I want to be able to find people either by their name and by their address. Both keys won't be used at the same time: I want to be able to call find(name) and find(address). Also, objects of the Person class won't be added or removed from the datastructure that often, but lookups will happen often. So lookups should ideally be fast. Edit 3: Storing pointers to the objects in the set instead of the objects themselves seems like a good solution. But would it be possible to store pointers in both sets? I.e. std::set<A*> set_sorted_by_key1; std::set<A*> set_sorted_by_key2; A *obj_p = new A(); set_sorted_by_key1.insert(obj_p); set_sorted_by_key2.insert(obj_p);
Storing pointers to the objects in the set instead of the objects themselves seems like a good solution. But would it be possible to store pointers in both sets? Sure, your sets seem to share ownership of that objects, so: class Person { std::string name; std::string address; // other fields }; using PersonPtr = std::shared_ptr<Person>; Now you want to sort them by name: struct CmpName { using is_transparent = void; bool operator()( const PersonPtr &p1, const PersonPtr &p2 ) const { return p1->name < p2->name; } bool operator()( const std::string &s, const PersonPtr &p2 ) const { return s < p2->name; } bool operator()( const PersonPtr &p1, const std::string &s ) const { return p1->name < s; } }; std::set<PersonPtr,CmpName> byName; Note type alias using is_transparent = void; and two additional methods are to enable equivalent search in std::set otherwise you would have to create instance of std::shared pointer<Person> just to to lookup. Details can be found here What are transparent comparators? And search it: auto f = byName.find( "John" ); Here how it works: Live example Searching by address can be done very similar way, just add another comparator struct and initialize std::set with it. Though you can store object and have multiple indexes using boost.multiindex but it has learning curve.
73,870,301
73,948,872
Why does ASIO not apply serial port settings when sending data (only receiving)?
I have a program that uses the modbus protocol to send chunks of data between a 64-bit Raspberry Pi 4 (running Raspberry Pi OS 64) and a receiving computer. My intended setup for the serial port is baud rate of 57600, 8 data bits, two stop bits, no flow control, and no parity. I have noticed that the data is only properly interpreted when the receiving computer is set to view one stop bit and no parity, regardless of the settings on the Raspberry Pi. What is interesting is this program works as expected when run on Windows, only the Pi has caused problems at the moment. This was originally seen in ASIO 1.20 and can still be reproduced in 1.24 on the Pi. I wrote a minimal example that reproduces the issue for me on the Pi: #include <asio.hpp> #include <asio/serial_port.hpp> #include <iostream> int main(void) { asio::io_service ioService; asio::serial_port serialPort(ioService, "/dev/serial0"); serialPort.set_option(asio::serial_port_base::baud_rate(57600)); serialPort.set_option(asio::serial_port_base::character_size(8)); serialPort.set_option(asio::serial_port_base::stop_bits(asio::serial_port_base::stop_bits::two)); serialPort.set_option(asio::serial_port_base::flow_control(asio::serial_port_base::flow_control::none)); serialPort.set_option(asio::serial_port_base::parity(asio::serial_port_base::parity::none)); std::string test("Test@"); asio::write(serialPort, asio::buffer(test.data(), test.size())); std::array<char, 5> buf; asio::read(serialPort, asio::buffer(buf.data(), buf.size())); std::cout << "Received: " << std::string(std::begin(buf), std::end(buf)) << std::endl; serialPort.close(); return 0; } I looked closer at the issue and used a Saleae Logic Analyzer to see what data is being sent between the machines. Below you can see the expected behavior for a successful run, this is when the test is run on Windows. Here you can see the behavior that occurs on the Raspberry Pi when it runs the test code. The analyzer fails to interpret the data using the parameters set in the code. Below you can see that when the analyzer is set with one stop bit rather than two, it interprets the hex without an issue. Overall you can see that the issue takes place on the Pi's end because of the responses seen in the logic analyzer. The program running on the Pi can interpret messages sent to it using the given parameters without any issue, however when it tries to reply to those messages it seems that the ASIO port settings are not being applied. Any insight that can be provided would be very helpful. Let me know if you need more information. Thanks for the help! UPDATE: Ran @sehe's test code as they recommended and results are as follows: baud_rate: Success character_size: Success stop_bits: Success flow_control: Success parity: Success parity: 0 (Success) flow_control: 0 (Success) stop_bits: 0 (Success) character_size: 8 (Success) baud_rate: 57600 (Success) ModbusTest: Main.cpp:37: int main(): Assertion `sb.value() == serial_port::stop_bits::two' failed. It appears that the setting for stop bits did not successfully apply and rather failed silently. Any ideas on how to proceed with further debugging? UPDATE 2: Also wanted to mention that I ran minicom with the same hardware setup and was able to communicate without issue using two stop bits.
I was able to discover the cause and fix the problem! I am using a Raspberry Pi 4 for this project and interfacing with GPIO pins 14/15 to use /dev/serial0. With the default configuration /dev/serial0 maps to /dev/ttyS0 which is a mini UART and is not capable of using multiple stop bits, etc. Disabling Bluetooth sets the symlink to map to /dev/ttyAMA0 which is a full UART and is capable of parity and multiple stop bits. In /boot/config.txt I added the following lines: [all] dtoverlay=disable-bt If you are experiencing a similar problem with /dev/serial0, this may be worth a shot.
73,870,453
73,870,546
Difference between std::reverse_iterator member functions: _Get_current() and base()?
Both member functions appear to do the same thing. In the example below, both return an iterator pointing to the same memory location. a) Is there any practical difference? b) Why cant I find any info for _Get_current() in the std class documentation? I suspect the underscore prefix is a clue. std::string s = std::string( "A B C" ) ; std::string::iterator iter1 = s.begin(); std::string::reverse_iterator iter2 = s.rbegin(); std::string::iterator iter3 = iter2.base(); std::string::iterator iter4 = iter2._Get_current();
If you ever see an identifier that starts with an _ followed by a capital letter, that identifier is being used by the internals of the C++ implementation and should never be used by you. You don't see it documented because it's for internal use only, specific to that implementation of the library type. Just use the actual interface.
73,870,625
73,870,771
pass rvalue to std::move and bind rvalue refence to it generate stack-use-after-scope error in ASAN
considering this code snippet #include <iostream> int foo() { int a; return a; } int main() { auto &&ret = std::move(foo()); std::cout << ret; } compile with ASAN g++ -fsanitize=address -fno-omit-frame-pointer -g -std=c++17 main.cpp -o main, run ./main shows error ==57382==ERROR: AddressSanitizer: stack-use-after-scope on address 0x00016b3cb480 at pc 0x000104a37e68 bp 0x00016b3cb450 sp 0x00016b3cb448 READ of size 4 at 0x00016b3cb480 thread T0 #0 0x104a37e64 in main main.cpp:8 #1 0x104a75084 in start+0x200 (dyld:arm64e+0x5084) But if I remove reference after auto, this piece of code can compile and run without an error given by ASAN. What I don't understand is that if std::move returns a reference to the object it is given, then that object, which is a temporary created by foo() in this example, will be destroyed after std::move function call return, so whether it is bind to rvalue reference or assigned to a new value should be invalid, because that temporary is already destroyed after move operation, right? Then why ASAN doesn't give an error in second case. ---------------------update---------------- #include <iostream> int foo() { int a = 1; return a; } int main() { auto &&ret = std::move(foo()); std::cout << ret; } if I don't compile with ASAN, this code will actually run without an error, it doesn't trigger segmentation fault or anything, and print 1 which is the same as a in foo funtion. and from the answers below I learned that the temporary is destroyed after auto &&ret = std::move(foo()); right? Is this an undefined behavior?
Assigning a prvalue (such as an int) to an auto&& variable will enable lifetime extension. The temporary will exist as long as your variable exists. Passing a prvalue to std::move() will convert the prvalue (int) to an xvalue (int&&). Lifetime extension no longer applies, and the temporary is destroyed before reaching std::cout << ret; This is why the presence of your std::move is triggering stack-use-after-scope. The move is preventing lifetime extension. The lesson: you likely never want to pass a prvalue (a temporary) to std::move.
73,872,417
73,872,438
How to declare assembly function with dynamic arguments in C++ like in C
I have some C code and I want to port it to c++, the problem is that in C++ I can't use an assembly function due to it's dynamic use C version extern asmFunc(); // C function prototype version //actual use example asmFunc(var1,ptr2,HANDLE); asmFunc(ptr4,var2,NULL,eg ...); //everything works C++ version extern "C" VOID asmFunc(); // C++ function prototype version //actual use example asmFunc(var1,ptr2,HANDLE); // E0140 too many arguments in function call asmFunc(ptr4,var2,NULL,eg ...); // E0140 too many arguments in function call The Assembly function is declared in a separate asm file and it uses direct syscalls from ntdll.dll's functions, that's why it requires dynamic arguments How to make it work?
Use ... in the argument list to specify the function is a variadic function taking unspecified arguments, eg: extern "C" VOID asmFunc(...); // C++ function prototype version //actual use example asmFUNC(var1,ptr2,HANDLE); asmFUNC(ptr4,var2,NULL,eg);
73,872,436
73,873,892
Adding values in an array by skipping one specific value in every iteration
I am trying to solve this problem from hours but could not find a solution. What I am trying to do is, I have an array of 4 indexes arr[4] = {7, 3, 2, 4}. Now the task is to add every element in every iteration but skipping that value on which iteration is going on. For example: input = arr[4] = {7, 3, 2, 4} 1st iteration : 3+2+4 = 9 2nd iteration : 7+2+4 = 13 3rd iteration : 7+3+4 = 14 4th iteration : 7+3+2 = 12 output = 9, 13, 14, 12. This is what I have tried: #include <iostream> int main() { int arr[4] = {7, 3, 2, 4}; int n = 4; int result = 0; int sum = 0; for(int i = 0; i < n; i++){ for (int j = 0; j < n; j++) sum += arr[j]; result = sum - arr[i]; std::cout << result<< ','; } return 0; } Actual Output 9,29,46,60, Expected Output 9, 13, 14, 12
You have to move your sum declaration inside the outer for loop, so that it gets reset at every outer iteration. Then in every inner iteration, you only add the element, if i!=j. Then you don't need to subtract anything from sum and you don't need the additional result variable. #include <iostream> int main() { int arr[4] = {7, 3, 2, 4}; int n = 4; int result = 0; for(int i = 0; i < n; i++){ int sum = 0; for (int j = 0; j < n; j++) if (i != j) sum += arr[j]; std::cout << sum<< ','; } return 0; } https://godbolt.org/z/7c9fG9j6K Functional approach using C++20 I highly suggest to use a more functional approach to programming as opposed to your procedural code. Two nested for-loops and managing two indices is error-prone and the code is hard to read. Consider the following C++20 code: #include <numeric> // for accumulate #include <ranges> #include <iostream> int main() { int arr[4] = {7, 3, 2, 4}; // calculate the sum of all elements auto sum = std::accumulate(std::begin(arr), std::end(arr), 0.0); // create a function (lambda) that subtracts sum from a double value auto subtract_from_sum = [sum](double const& value){ return sum - value; }; // transform the input array, by applying the minus_sum function to every // element auto res = arr | std::views::transform(subtract_from_sum); // print the result for (auto v: res) std::cout << v << " "; return 0; } https://godbolt.org/z/8P8eW7vf8 The code is not necessarily shorter, but instead of telling the computer the steps it has to perform, you tell the computer the result that you want to have. Let me walk you through the code: You use std::accumulate to sum all elements of your array. You define a lambda expression (basically a function) subtract_from_sum, that subtracts a double value from sum. std::views::transform lets you create a new array, where every element is transformed by a function. Here you use the "pipe operator" | to pipe the input array arr to std::views::transform, which takes the previously defined lambda as the function that is to be applied to every element. You output the result. All the ugly implementation details and for-loops are hidden away. It also has the additional benefit of being faster: With your approach, you sum n-1 values n times, so that you have n*(n-1) floating point operations. With this approach you sum n values and then perform n subtractions. So you have 2*n floating point operations in total. Functional approach using C++11/C++14/C++17 In older C++ standards, you can also use a functional approach, but the code is a bit more verbose without the ranges capability of C++20 #include <numeric> // for accumulate #include <vector> #include <algorithm> #include <iostream> int main() { int arr[4] = {7, 3, 2, 4}; // calculate the sum of all elements auto sum = std::accumulate(std::begin(arr), std::end(arr), 0.0); // create a function that subtracts sum from a double value auto subtract_from_sum = [sum](double const& value){ return sum - value; }; // transform the input array, by applying the subtract_from_sum function to every // element std::vector<double> res; std::transform( std::begin(arr), std::end(arr), std::back_inserter(res), subtract_from_sum ); // print the result for (auto v: res) std::cout << v << " "; return 0; } https://godbolt.org/z/avvxdnWEe
73,872,461
73,872,596
Error: expected primary-expression before ']' token. Need assitance with function definition and calling
This is my first semester of computer science, and I need help with my first project. So far, it's still a mess, and I am mainly doing test cases to ensure basic things like my functions work. The goal of the project is to ask the user how many robots they want to make, name them, then they can use the robot's name (their unique identifier) to move the robots along an X-Y axis, which is really just the program adding or subtracting to a .Xvalue or .Yvalue. My MenuFunction works, but I am having trouble with the MoveFunction. Basically, I want the MoveFunction to ask the user which robot they want to use, go through the RobotArray, and print the Robot's name once found. Again, this is just a test case so I can better understand the coding. Right now, I am getting two errors: main.cpp:42:33: error: expected primary-expression before ‘]’ token 42 | string MoveFunction(RobotArray[], robotName, NumberOfRobots); main.cpp:62:16: error: no match for call to ‘(std::string {aka std::__cxx11::basic_string}) ()’ 62 | MoveFunction(); I don't know what to do for the first error, but I think the latter is due to my not having any objects in the function call, but I wouldn't know what to put in there anyway. My complete code is below: #include <iostream> using namespace std; struct userRobot { string name; int Xvalue = 0; int Yvalue = 0; }; void MenuFunction() { cout << "Welcome to MultiRobo Guider." << endl; cout << "Please select:" << endl; cout << "m - move" << endl << "d - distance" << endl << "q - quit" << endl << endl; } int main() { int NumberOfRobots; string robotName; cout << "Enter the number of robots" << endl; cin >> NumberOfRobots; cout << endl << "Enter their name(s)" << endl; userRobot RobotArray[NumberOfRobots]; for (int i = 0; i < NumberOfRobots; i++) { cin >> robotName; RobotArray[i].name = robotName; } cout << endl; for (int j = 0; j < NumberOfRobots; j++) { cout << RobotArray[j].name << "'s position is "; cout << "(" << RobotArray[j].Xvalue << "," << RobotArray[j].Yvalue << ")" << endl << endl; } string MoveFunction(RobotArray[], robotName, NumberOfRobots); { cin >> robotName; for (int k = 0; k < NumberOfRobots; k++) { if (robotName == RobotArray[k].name) { cout << RobotArray[k].name; } } } MenuFunction(); char input; cin >> input; if (input == 'm') { cout << "Which robot would you like to move?"; MoveFunction(); } else if (input == 'd') { cout << "distance"; } else if (input == 'q') { cout << "quit"; } }
First off, userRobot RobotArray[NumberOfRobots]; is a variable-length array, which is a non-standard extension supported by only a few compilers. To create an array whose size is not known until runtime, you should use new[] instead, or better std::vector. That said, your main issue is that you are trying to define your MoveFunction() function inside of your main() function, which is not allowed. But, even if it were, you are not declaring it correctly. It has an erroneous ; on it. And RobotArray, robotName, and NumberOfRobots are not types, but variables. Like a variable, a function parameter always starts with a type. There are no untyped parameters/variables in C++. You need to either: move MoveFunction() outside of main(), and fix its declaration to use proper types, eg: #include <iostream> #include <vector> #include <string> using namespace std; struct userRobot { string name; int Xvalue = 0; int Yvalue = 0; }; void MenuFunction() { cout << "Welcome to MultiRobo Guider." << endl; cout << "Please select:" << endl; cout << "m - move" << endl << "d - distance" << endl << "q - quit" << endl << endl; } void MoveFunction(userRobot RobotArray[], int NumberOfRobots) { cout << "Which robot would you like to move?"; string robotName; cin >> robotName; for (int k = 0; k < NumberOfRobots; k++) { if (robotName == RobotArray[k].name) { cout << RobotArray[k].name << endl; return; } } cout "Robot not found" << endl; } int main() { cout << "Enter the number of robots" << endl; int NumberOfRobots; cin >> NumberOfRobots; vector<userRobot> RobotArray(NumberOfRobots); cout << endl << "Enter their name(s)" << endl; for (int i = 0; i < NumberOfRobots; i++) { cin >> RobotArray[i].name; } cout << endl; for (int j = 0; j < NumberOfRobots; j++) { cout << RobotArray[j].name << "'s position is "; cout << "(" << RobotArray[j].Xvalue << "," << RobotArray[j].Yvalue << ")" << endl << endl; } MenuFunction(); char input; cin >> input; if (input == 'm') { MoveFunction(RobotArray.data(), NumberOfRobots); } else if (input == 'd') { cout << "distance"; } else if (input == 'q') { cout << "quit"; } } or change MoveFunction() into a lambda, eg: #include <iostream> #include <vector> #include <string> using namespace std; struct userRobot { string name; int Xvalue = 0; int Yvalue = 0; }; void MenuFunction() { cout << "Welcome to MultiRobo Guider." << endl; cout << "Please select:" << endl; cout << "m - move" << endl << "d - distance" << endl << "q - quit" << endl << endl; } int main() { cout << "Enter the number of robots" << endl; int NumberOfRobots; cin >> NumberOfRobots; vector<userRobot> RobotArray(NumberOfRobots); cout << endl << "Enter their name(s)" << endl; for (int i = 0; i < NumberOfRobots; i++) { cin >> RobotArray[i].name; } cout << endl; for (int j = 0; j < NumberOfRobots; j++) { cout << RobotArray[j].name << "'s position is "; cout << "(" << RobotArray[j].Xvalue << "," << RobotArray[j].Yvalue << ")" << endl << endl; } auto MoveFunction = [&]{ cout << "Which robot would you like to move?"; string robotName; cin >> robotName; for (int k = 0; k < NumberOfRobots; k++) { if (robotName == RobotArray[k].name) { cout << RobotArray[k].name << endl; return; } } cout "Robot not found" << endl; }; MenuFunction(); char input; cin >> input; if (input == 'm') { MoveFunction(); } else if (input == 'd') { cout << "distance"; } else if (input == 'q') { cout << "quit"; } }
73,873,332
73,873,357
Error C2280 in a simple piece of C++ code
I'm trying to solve a "stupid" problem I got with Visual Studio Enterprise 2022. I created a new MFC application from scratch, then I added this single line of code: CFile testFile = CFile(_T("TEST STRING"), CFile::modeCreate); When I try to build the solution, I get this error from the compiler: error C2280: 'CFile::CFile(const CFile &)': attempting to reference a deleted function I read lot of answers and also the official MS Guide about this error but I still cannot figure how to solve. Any hint?
CFile objects can't be copied, but that is exactly what you are trying to do - you are creating a temporary CFile object and then copy-constructing your testFile from it. 1 Use this instead to avoid the copy and just construct testFile directly: CFile testFile(_T("TEST STRING"), CFile::Attribute::normal); 1: I would be very worried by the fact that the compiler is even complaining about this copy, instead of just optimizing the temporary away, as all modern C++ compilers are supposed to do. This statement: CFile testFile = CFile(_T("TEST STRING"), CFile::Attribute::normal); Is effectively just syntax sugar for this (hence the delete'd copy constructor being called): CFile testFile(CFile(_T("TEST STRING"), CFile::Attribute::normal)); Which modern compilers since C++17 onward are supposed to optimize to this: CFile testFile(_T("TEST STRING"), CFile::Attribute::normal); However, at least according to MSDN, Visual Studio defaults to C++14 by default. So make sure you are compiling for a later C++ version instead.
73,873,635
73,873,736
Why are `function<void (string)>` and `function<string (string)>` parameter types sometimes ambiguous for overloading?
Following up my question c++ - How do implicit conversions work when using an intermediate type?, from which I understood the rule of 1 implicit conversion max, I'm trying to understand a more advanced use case involving function arguments. Let's say I have a function, which accepts as a parameter another function. That function parameter could either return something, or return nothing (void). Therefore, I want to overload the function definition, to accept in one case the non-void function argument, and in the other case the void function argument. using VoidType = void (string); using NonVoidType = string (string); string call(VoidType *fn, string arg) { cout << "[using void function]" << endl; fn(arg); return arg; } string call(NonVoidType *fn, string arg) { cout << "[using non void function]" << endl; return fn(arg); } When calling the function, the given argument has a known type, so the overload selection should be straightforward, such as here: void printVoid(string message) { cout << message << endl; } string printNonVoid(string message) { cout << message << endl; return message; } void test() { call(printVoid, "call(printVoid)"); call(printNonVoid, "call(printNonVoid)"); } But it's not when I have intermediate types, such as std::function wrappers: string call(function<VoidType> fn, string arg) { cout << "[using void function]" << endl; fn(arg); return arg; } string call(function<NonVoidType> fn, string arg) { cout << "[using non void function]" << endl; return fn(arg); } void test() { call(printVoid, "call(printVoid)"); call(printNonVoid, "call(printNonVoid)"); // more than one instance of overloaded function "call" matches the argument list:C/C++(308) } for which I get the error more than one instance of overloaded function "call" matches the argument list:C/C++(308) on the second call. A solution to this is to instantiate the std::function explicitly before calling: void test() { call(function(printNonVoid), "call(function(printNonVoid))"); } But, how is call(function(printNonVoid), "xxx") so different from call(printNonVoid, "xxx") knowing that in the latter case I would expect the implicit conversion to do the equivalent to what is done in the former case. Am I missing something, like some intermediate, hidden copy constructors or whatever? Full example: #include <iostream> using namespace std; using VoidType = void (string); using NonVoidType = string (string); string callFromPointer(VoidType *fn, string arg) { cout << "[callFromPointer] void" << endl; fn(arg); return "<void>"; } string callFromPointer(NonVoidType *fn, string arg) { cout << "[callFromPointer] non void" << endl; return fn(arg); } string callFromFunction(function<VoidType> fn, string arg) { cout << "[callFromFunction] void" << endl; fn(arg); return "<void>"; } string callFromFunction(function<NonVoidType> fn, string arg) { cout << "[callFromFunction] non void" << endl; return fn(arg); } void printVoid(string message) { cout << "\t[printVoid] " << message << endl; } string printNonVoid(string message) { cout << "\t[printNonVoid] " << message << endl; return message; } void sep() { cout << "\n----\n" << endl; } void main() { callFromPointer(printVoid, "callFromPointer(printVoid)"); callFromPointer(printNonVoid, "callFromPointer(printNonVoid)"); sep(); callFromFunction(printVoid, "callFromFunction(printVoid)"); callFromFunction(printNonVoid, "callFromFunction(printNonVoid)"); // more than one instance of overloaded function "callFromFunction" matches the argument list:C/C++(308) sep(); callFromFunction(function(printVoid), "callFromFunction(function(printVoid))"); callFromFunction(function(printNonVoid), "callFromFunction(function(printNonVoid))"); }
This is because std::string(*)(std::string) is "compatible" with both std::function<void(std::string)> and std::function<std::string(std::string)> since the former can simply ignore the underlying function's return value. That is, both of the following are valid: std::function<void(std::string)> voidFunc(printNonVoid); std::function<std::string(std::string)> strFunc(printNonVoid); Since neither is a "better" match, overload resolution fails when calling callFromFunction(printNonVoid, "..."). The reason it works when using std::function(printNonVoid) is because class template argument deduction takes over, and there is a deduction guide for T(*)(Args...) -> std::function<T(Args...)>. That deduction guide turns std::function(printNonVoid) into std::function<std::string(std::string)>(printNonVoid). Since that's an exact match with no conversion necessary for the std::function<std::string(std::string)> overload of callFromFunction that overload is chose by overload resolution. That deduction guide doesn't come into play when performing overload resolution with just the raw function name though, since the function arguments have to explicitly declare std::function's template argument.
73,873,893
73,873,962
Time Complexity of nested for loops with different conditions
What would be the time complexity for this snippet? I'm having a little trouble understanding how to find the time complexity of nested for loops with different conditions. I originally thought that it would be n^3 x n^2 which gives O(n^5), but should it be (n^3)^2 which gives O(n^6)? for(int i = 0; i < n*n; i++) { for(int j = 0; j < n*n*n; j++) { A(); //O(1) } }
If you correctly incremented j in the inner loop (replacing i++ with j++ in the inner loop increment step), it would be O(n⁵). The outer loop runs the inner loop n² times, with each inner loop running n³ times; the total is strictly multiplicative, n² * n³ == n⁵. As written, it'll never stop running if n > 1 (because j never increments, so if the inner loop begins running, it runs forever).
73,873,989
73,886,473
Is there a g++ flag that can detect and warn about this unreachable code in a switch statement?
This isn't quite the minimum possible reproduction, but hopefully illustrates the issue well while being bite-sized. #include <iostream> int main(int, char **) { int i; std::cin >> i; switch(i) { case 0: break; std::cout << "too small" << std::endl; case 1: break; default: std::cout << "too large" << std::endl; break; } return 0; } The problem here, of course, is that the user has added code to a switch statement after the break instead of before it. (Of course in a real example there would have been preexisting code prior to the break statement) clang is able to detect this with the -Wunreachable-code flag, and MSVC is able to detect it with /Wall, but I haven't found a way to get g++ to warn about this. g++ does have a flag -Wswitch-unreachable, but that only catches code that appears prior to the first switch label, so it's of no help here.
This is basically resolved in the comments by Eljay and Jerry Jeremiah, but for the sake of closing the question out, it looks like gcc silently removed unreachable code detection back in 2014 because it gave different results at different optimization levels. This seems like a remarkably stupid justification for removing one of the most basic and important features every compiler is supposed to have, but what do I know? From the gcc mailing list: The -Wunreachable-code has been removed, because it was unstable: it relied on the optimizer, and so different versions of gcc would warn about different code. The compiler still accepts and ignores the command line option so that existing Makefiles are not broken. In some future release the option will be removed entirely. Source: https://gcc.gnu.org/legacy-ml/gcc-help/2011-05/msg00360.html
73,874,619
73,956,681
Compilation issue on mac Error: No matching constructor for initialization of 'wavenet::WaveNet'
I have a Compilation issue on mac, I'm trying to build this Neural Amp Modeler https://github.com/sdatkinson/iPlug2/tree/main/Examples/NAM on a Apple M1 MBP macOS 12.6 / Xcode 14.0 The code in that repository works on Windows but on my machine I get these errors: Error: No matching constructor for initialization of 'wavenet::WaveNet' In instantiation of function template specialization: 'std::make_unique<wavenet::WaveNet, std::vector<wavenet::LayerArrayParams> &, const float &, const bool &, nlohmann::basic_json<>, std::vector<float> &>' In file included from /Users/username/Dev/iPlug2/Examples/NAM/get_dsp.cpp note: wavenet.h note: candidate constructor not viable: expects an lvalue for 4th argument note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 5 were provided note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 5 were provided' I don't understand why it works on windows, I can post more code if need it and all the files are on the repository, Thanks!
I made a quick guess based on my experiences (Unfortunately, I cannot test it on a Mac). Since the compile error comes from get_dsp.cpp we should try to fix it there before trying to change something in the class WaveNet itself. The make_unique call is issued in get_dsp.cpp, line 83. In line 87 is the 4th parameter to the constructor: architecture == "CatWaveNet" ? config["parametric"] : nlohmann::json{} I guess the default constructed nlohmann::json after the : is the root source of the compile error. This creates an un-named temporary object which is an rvalue. But the constructor requires an lvalue (non-const reference to a nlohmann::json). To fix that we must ensure we pass something which can act as an lvalue, so we need a named object, like this: auto my_json = architecture == "CatWaveNet" ? config["parametric"] : nlohmann::json{}; This must be placed before the return statement in line 82 and then use "my_json" as constructor parameter in line 87. The complete changed block will then look like this: auto my_json = architecture == "CatWaveNet" ? config["parametric"] : nlohmann::json{}; return std::make_unique<wavenet::WaveNet>( layer_array_params, head_scale, with_head, my_json, params ); Does it solve the problem?
73,875,331
73,875,348
Is it an UB when I try to pass the address of temporary as argument?
For the following C++ codes: #include <iostream> using namespace std; class A { public: A() { cout << "A()\n"; } ~A() { cout << "~A()\n"; } A* get() { return this; } // <------ }; void f(const A * const &a, const A * const &b) { cout << "f()\n"; } int main() { // f(&A(), &A()); // error: taking address of temporary f(A().get(), A().get()); // <------ cout << "end\n"; return 0; } And it returns: A() A() f() ~A() ~A() end Of course I can't use &A() here because this leads to an error: error: taking address of temporary. But it works when I wrapped it in A* get() { return this; }. So my question is, is it an Undefined Behaviour to use get()?
So my question is, is it an Undefined Behaviour to use get()? No, it's not undefined behavior. It's valid because the temporary object is first constructed, then the function is called, and then (only after the function returns) is the temporary object destroyed again. So during the lifetime of the function call, you're allowed to do anything you could normally do with the passed-in temporary object, including dereferencing a pointer to it or its contents. (your function shouldn't store the passed-in pointer for later use, though, since it will become a dangling-pointer as soon as the function returns!)
73,875,402
73,875,469
Why does std::map crash when it is declared static inline inside a class and used early?
I have found several times that when a std::map is declared inside a class as a static inline (C++ 17), struct MyStruct { static inline std::map <A, B> mymap; MyStruct(A& a, B& b) { mymap[a] = b; } }; the MyStruct constructor will crash if it is called early, i.e. before main, inside the first use of the map member. If the std::map is declared a different way, i.e., struct MyStruct { static std::map <A, B>& mymap() { static std::map <A, B> map; return map; } MyStruct(A& a, B& b) { mymap()[a] = b; } }; then no crash happens. I would have thought that in both cases the map would be initialized before the call to MyStruct constructor would be allowed to proceed. Can anyone explain what is happening here?
Declaring a static inline class member effectively ODR-defines that class member in some randomly-chosen translation unit that forms the final executable. At this point Static Initialization Order Fiasco becomes a factor when the class member gets referenced in a translation unit in the manner you described. This results in undefined behavior. The function-scoped static class instance is a well known technique for defeating the static initialization order fiasco. Function-scoped static objects have well-defined initialization semantics: the first time the function gets called, from any translation unit.
73,875,833
73,875,956
Meaning of code involving function binding
Can someone explain what is going on in the below code snippet line by line auto enq_func = [](std::queue<reg_t>* q, uint64_t x) { q->push(x); }; std::queue<reg_t> fromhost_queue; std::function<void(reg_t)> fromhost_callback = std::bind(enq_func, &fromhost_queue, std::placeholders::_1); I think I get the gist of it, that fromhost_queue is a std::queue of each element of type reg_t which was typedef in the beginning of the code as uint64_t and its enqueue functionality is defined using the above three lines something like that. I have trouble understanding line 1 as I haven't come across this type of function declaration like =[](...){...}; is this some sort of shorthand or something Also, in the bind() part in line 3, the first argument is a function(here named as enq_func) that bind will be applied on the second argument mostly used to pass a reference of a queue the enq_func will be applied but the last is an argument which will we enqueued but I don't see the enq_func having any arguement can someone clarify this?
This is a slightly overly-complex way to create a function-like callable object that pushes its argument into fromhost_queue. That is, fromhost_callback(123) will end up calling fromhost_queue.push(123). auto enq_func = [](std::queue<reg_t>* q, uint64_t x) { q->push(x); }; This is a lambda expression that creates a callable object that pushes its second parameter into the queue pointed to by the first parameter. That is, enq_func(&fromhost_queue, 123) will call fromhost_queue.push(123). std::function<void(reg_t)> fromhost_callback = std::bind(enq_func, &fromhost_queue, std::placeholders::_1); This creates a new callable object that wraps enq_func and automatically supplies its first argument, then stores that in a type-erased std::function container. So fromhost_callback(123) will automatically call enq_func(&fromhost_queue, 123). There's no reason to do this in two steps though, a single lambda will do fine. Assuming there's a good reason to use std::function then this will do the same thing: std::queue<reg_t> fromhost_queue; std::function<void(reg_t)> fromhost_callback = [&fromhost_queue](uint64_t x) { fromhost_queue.push(x); }
73,876,624
73,876,653
Classes not giving required output in c++
I have created a class name Employee and inside that I have declared a function and two variable(name ,age) . After creating a variable x I am not getting the name insted getting empty name and age =0 CODE: #include<iostream> using namespace std; class Employee{ public: string name; int age; void print(){ cout<<"Name:"<<name<<endl; cout<<"Age:"<<age<<endl; } Employee(string name,int age){ name = name; age=age; } }; int main(){ Employee x=Employee("chang",33); x.print(); return 0; } Expected: name:Chang age :33 OutPut: name: age :0 Can Someone tell me what is the reason behind it.
Employee(string name, int age) { name = name; age = age; } you are not modifying the class members, but the parameters instead. You have three ways to solve this problem: use this-> to precisely target the right variables. Employee(string name, int age) { this->name = name; this->age = age; } use an initialisation list: Employee(string name, int age) : name(name), age(age) { } don't use any constructor, but use brace initialization instead: int main() { Employee x = Employee{ "chang", 33 }; x.print(); } I would personally use option three with the braces, as it's the most efficient to write. read here why you shouldn't be using namespace std;
73,876,979
73,878,956
C++ Convert string logical expression to conditional expression
I have a logical expression in string and need to evaluate. Is there a way in C++ do it? std::string exp = "(1||0)&&(1&&1)&&(1||0&&0)"; Eg: if ((1 || 0) && (1 && 1) && (1 || 0 && 0)) { std::cout << "true\n"; }
There's no easy built-in way in C++ to evaluate logic expressions like that. If you want to evaluate such an expression in runtime, you need to parse a string into some intermediate representation first (e.g. an expression tree) by writing a parser and write an evaluator that will flatten that tree into a single value. Then, assuming struct ExprTree { ... }; ExprTree parse(std::string const& input); bool eval(ExprTree const& expr); you can get the result of such a string expression with std::string exp = "(1||0)&&(1&&1)&&(1||0&&0)"; if (eval(parse(exp)) { // ... }
73,877,598
73,954,016
GRPC with one server and several clients
Q1: When I have a GRPC connection with one server(S) and several clients(C1 and C2)(Using Response-streaming RPC). I wonder how frames S sends to C1 and C2? For example, there's 10 frames that server needs to response. What will C1 and C2 receive separately and Why? C1 gets 5 frames and C2 gets another 5(I tried my program and seems it acts like this way) C1 gets all 10 frames C2 gets the same all 10 copies. And is there a way to choose from 1 or 2? Q2: a GRPC connection with only one server(S) and only one client(C) this time(Using Response-streaming RPC still). I forcely stop C(i.e. ctrl+c) and restart the program(C_second).But this time C_second still only gets parts of frames that S sends. Seems the connection between S and C(forcely stopped) still be alive?
gRPC is point-to-point. The connection C1 -> S and C2 -> S are separate. Any message that S sends will be directed at either C1 or C2. If duplication is required between clients, the server application logic will need to manage this itself. Great question. This is a point that people often miss in designing their protocol. gRPC itself is stateless. If a channel dies, the client will not attempt to download previously sent messages. Instead, the RPC needs to be made idempotent or stateful. That is, if checkpointing needs to happen in a streaming API, the application needs to manage that itself.
73,878,113
73,878,716
Repeatedly non-stop output when I input char into int variable
The folowing code tells user to input their age, it is set to be input interger between 0 and 120, it is capable to deal with wrong input like 'M' or 133 or -1. Warning message goes like this:Warning message case 1: // input age cout << "Enter your age: "; cin >> age; if(age <= 0 || age > 120){ // if the input type or number was wrong, it goes here while(1){ cout << "Invalid input! Please enter again" << endl << ">>>"; age = -1; cin >> age; if(age > 0 && age <= 120) {break;} } } However, it'll go wrong if I input something like \ or [. Repeating Warning message How can I solve this?
By emptying the keyboard buffer before a new entry. #include <iostream> #include <limits> using namespace std; int main() { int age; cout << "Enter your age: "; cin >> age; while(age <= 0 || age > 120) { cout << "Invalid input! Please enter again" << endl << ">>>"; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin >> age; } return 0; }
73,878,221
73,878,245
Static pointer to a class method, if possible and meaningful
Usually for singleton classes, one has to write all the time something like this: SomeSingleton::GetInstance().someVariable And I'm looking for a simplification that can be seen everywhere, so should be put in the (header and source) files of the class itself. So, the (non-working) stuff should look something like this: SomeSingleton.hpp: class SomeSingleton { //... static SomeSingleton& GetInstance(); }; SomeSingleton& (*INSTANCE)(); SomeSingleton.cpp: SomeSingleton& (* INSTANCE)() = SomeSingleton::GetInstance; But this is misinterpreted as a redefinition, so doesn't work. If the declaration and the definition was in the same row, that would work, but then it would not work in a header used from everywhere. Assigning the pointer to the already declared INSTANCE variable wouldn't be simpler than simply defining the INSTANCE every file it is used in. A workaround is to put a line static SomeSingleton& (*INSTANCE)() = SomeSingleton::GetInstance; into every file I use this and replace every SomeSingleton::GetInstance to INSTANCE which works but not ideal plus I'm not sure that from a design aspect it is clever to assign a singleton to a static variable (in a sense a static stuff to another static stuff). Any ideas on this?
I think the only thing you are missing is extern in your header extern SomeSingleton& (*INSTANCE)();
73,878,908
73,880,020
Is it possible to devirtualize this method call with GCC?
In the piece of code below, I expect the a->f2() call to be devirtualized, providing all compiler optimizations are enabled (-O3). #include <memory> #include <iostream> class AbstractA { public: virtual ~AbstractA() = default; virtual void f1() = 0; virtual void f2() { std::cout << "AbstractA::f2" << std::endl; this->f1(); } }; class ConcreteA final : public AbstractA { int x_; public: /*void f2() override { this->f1(); }*/ void f1() override { std::cout << "ConcreteA::f1" << std::endl; x_++; } int get() const { return x_; } }; int main() { auto a = std::make_unique<ConcreteA>(); a->f2(); return a->get(); } While clang appears to deal with it properly by inlining subsequent method calls, yet GCC introduces a vtable and seems to use it later in the assembly (see here). movq $vtable for ConcreteA+16, (%rax) call AbstractA::f2() ... movq 16(%rax), %rax cmpq $ConcreteA::f1(), %rax jne .L17 I am aware that the C++ standard does not enforce compilers to optimize by devirtualization. Nonetheless, my question is: is there anything that can be done so that GCC optimizes the call by omitting a vtable lookup?
Assuming you know that AbstractA::f2 is not a pure member function, then you can simply override it explicitly from ConcreteA so GCC can inline AbstractA::f2 and so ConcreteA::f1: // In ConcreteA: void f2() override { AbstractA::f2(); } The vtable is still present due to a missing global optimization (GCC appears to consider that classes could possibly be used from outside while Clang know it is not the case, not to mention it better track pointers). CRTP may help to fix that if this is a problem. Theoretically, GCC has all the information here so to optimize the code without any modification but it does not due to missing optimization yet. Using Profile-Guided Optimizations (PGO) with Link-Time Optimizations (LTO) can help a lot to speculatively devirtualize member function calls (since GCC can know that there is no other classes using AbstractA, ConcreteA is only used in the main, better track pointers, etc.).
73,879,411
73,879,610
C++ Error: error: expected unqualified-id before string constant
What should I do in this line of code (highlighted by comment) ? # include <iostream> int main() { int occurrences = 0; std::string::size_type start = 0; std::string base_string = "Hello World in C++!"; std::string to_find_occurrences_of = "o","+"; // error while ((start = base_string.find(to_find_occurrences_of, start)) != std::string::npos) { ++occurrences; start += to_find_occurrences_of.length(); } std::cout<<occurrences; return 0; } I want string to_find_occurrences_of = "o","+" to print the two characters in one time (but IDE raises an error) because I do not want to define the string (and the function) over and over again to find the occurrences of the characters in string base_string one by one. It may sound like a stupid question, but I want to know the solution to this error. Thank you to anyone who may be reading this question or answering!!!
std::string to_find_occurrences_of = "o","+"; won't compile, because you have two strings, rather than one. You could just have an initialiser list of the things to find: int main() { int occurrences = 0; // std::string::size_type start = 0; // need to reset for each character std::string base_string = "Hello World in C++!"; for (std::string to_find_occurrences_of : { "o", "+" }) // OK { std::string::size_type start = 0; // start from the beginning for each character while ((start = base_string.find(to_find_occurrences_of, start)) != std::string::npos) { ++occurrences; start += to_find_occurrences_of.length(); } } std::cout << occurrences; }
73,880,034
73,880,075
Operator>> overloading: "cannot bind 'std::istream {aka std::basic_istream<char>}' lvalue to 'std::basic_istream<char>&&'"
Here's my fraction class: class fraction { // type definition int num; int denom; ostringstream sstr; public: fraction(int c=0, int d=1) : num(c), denom(d) { sstr = ostringstream(); } fraction(const fraction &f) : num(f.num), denom(f.denom) { /*void*/ } friend ostream& operator<<(ostream &os, const fraction &f){ os << "(" << f.num << "/" << f.denom << ")"; return os; } friend istream& operator>>(istream &is, const fraction &f){ is >> "(" >> f.num >> "/" >> f.denom >> ")"; // Exception thrown on this line on "is >>" return is; } Overloading the operator<< works, but operator>> throws an error: cannot bind 'std::istream {aka std::basic_istream<char>}' lvalue to 'std::basic_istream<char>&&' I have looked at other questions here on SO, but still have no idea why this could be. I think it might have something to do with pointers, but I am clueless. Please note that I'm really new to C++, so there might be some obvious flaws in my code, feel free to point them out in a comment.
Remove the const: friend istream& operator>>(istream &is, fraction &f){ Clearly, since operator>> is modifying f, it should not be const. On the other hand, the const in operator<< is correct, because that function does not modify f. Also, is >> "(" is incorrect. Not clear what you intend by that, but you cannot read into a string literal. You can only read into variables (more or less). BTW, that's not an exception being thrown on that line, it's an error message being generated from that line. An exception is something completely different.
73,880,279
73,956,879
Unable to successfully instantiate BreakIterator even after u_setDataDirectory was set
I am using ICU's BreakIterator (icu 68.2) for word segmentation. I have used u_setDataDirectory to initialise the data path as mentioned in below code snippet's 1st line. But when I check the status of createWordInstance(), I am getting U_MISSING_RESOURCE_ERROR. This kind of error should be solved by calling u_setDataDirectory. I have used that, but the problem is still there. u_setDataDirectory; UErrorCode status = U_ZERO_ERROR; BreakIterator *wordIterator = BreakIterator::createWordInstance(Locale("zh"), status); if (U_FAILURE(status)) { std::cout<<"failed to create break iterator. status = "<<u_errorName(status)<<std::endl; exit 1; } UnicodeString text = "sample input string"; wordIterator->setText(text); delete wordIterator;
If u_setDataDirectory is the only cause for your error, you must call it with the correct path to the data directory. change your first line from u_setDataDirectory; to (on Linux/Unix) u_setDataDirectory( "/path/to/ICU/data/" ); or on Windows to u_setDataDirectory( "C:\\Path\\To\\ICU\\Data\\" ); Unfortunately I don't know where are the data files of ICU. You need to correct the path string to the correct path on your system. But from the reading of the ICU documentation https://unicode-org.github.io/icu-docs/apidoc/dev/icu4c/putil_8h.html#a550ea8502df5fed47ae4359be7f8e6a2 I guess, this is not enough to solve your problem. If the call above does not solve your problem, you can try to call u_init( UErrorCode *status ) as the very first statment: UErrorCode status = U_ZERO_ERROR; u_init( &status ); if (U_FAILURE(status)) { std::cout<<"failed to init. status = "<<u_errorName(status)<<std::endl; std::exit( 1 ); } and then check what is the problem. EDIT A second root cause can be that the "Locale("zh")" is missing. Does it work with other locales? Like change it to "en_US" ? You can also test if the Locale works by this: if( Locale("zh").isBogus() ) { std::cout << "Locale is not working!" << std::endl; std::exit( 1 ); }
73,880,594
73,880,888
static_cast to the base of base class with protected inheritance
I don't quite understand why below code is not legal. struct A { int a; }; struct B : protected A { int b; }; struct C : B { int c; } tc; const A &ra = static_cast<A &>(tc); Could someone help to explain it? Thank you very much.
The public, protected and private specifiers let access in different-wide areas. You can access protected members only in your class functions or its heirs. For example that code works: struct A { int a; }; struct B : protected A { int b; }; struct C : /*implicit `public` because C is struct but not class*/ B { int c; void foo(C &tc) { const A &ra = static_cast<A &>(tc); // Because `foo` can access to A instead of outside code like yours. } };
73,880,798
73,884,081
Drake: Integrate Mass Matrix and Bias Term in Optimization Problem
I am trying to implement Non Linear MPC for a 7-DOF manipulator in drake. To do this, in my constraints, I need to have dynamic parameters like the Mass matrix M(q) and the bias term C(q,q_dot)*q_dot, but those depend on the decision variables q, q_dot. I tried the following // finalize plant // create builder, diagram, context, plant context ... // formulate optimazation problem drake::solvers::MathematicalProgram prog; // create decision variables ... std::vector<drake::solvers::VectorXDecisionVariable> q_v; std::vector<drake::solvers::VectorXDecisionVariable> q_ddot; for (int i = 0; i < H; i++) { q_v.push_back(prog.NewContinuousVariables<14>(state_var_name)); q_ddot.push_back(prog.NewContinuousVariables<7>(input_var_name)); } // add cost ... // add constraints ... for (int i = 0; i < H; i++) { plant.SetPositionsAndVelocities(*plant_context, q_v[i]); plant.CalcMassMatrix(*plant_context, M); plant.CalcBiasTerm(*plant_context, C_q_dot); } ... for (int i = 0; i < H; i++) { prog.AddConstraint( M * q_ddot[i] + C_q_dot + G >= lb ); prog.AddConstraint( M * q_ddot[i] + C_q_dot + G <= ub ); } // solve prog ... The above code will not work, because plant.SetPositionsAndVelocities(.) doesn't accept symbolic variables. Is there any way to integrate M,C in my ocp constraints ?
I think you want to impose the following nonlinear nonconvex constraint lb <= M * qddot + C(q, v) + g(q) <= ub This constraint is non-convex. We will need to solve it through nonlinear optimization, and evaluate the constraint in every iteration of the nonlinear optimization. We can't do this evaluation using symbolic computation (it would be horribly slow with symbolic computation). So you will need a constraint evaluator, something like this // This constraint takes [q;v;vdot] and evaluate // M * vdot + C(q, v) + g(q) class MyConstraint : public solvers::Constraint { public: MyConstraint(const MultibodyPlant<AutoDiffXd>& plant, systems::Context<AutoDiffXd>* context, const Eigen::Ref<const Eigen::VectorXd>& lb, const Eigen::Ref<const Eigen::VectorXd>& ub) : solvers::Constraint(plant.num_velocitiex(), plant.num_positions() + 2 * plant.num_velocities(), lb, ub), plant_{plant}, context_{context} { ... } private: void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const { ... } MultibodyPlant<AutoDiffXd> plant_; systems::Context<AutoDiffXd>* context_; }; int main() { ... // Construct the constraint and add it to every time instances std::vector<std::unique_ptr<systems::Context<AutoDiffXd>>> plant_contexts; for (int i = 0; i < H; ++i) { plant_contexts.push_back(plant.CreateDefaultContext()); prog.AddConstraint(std::make_shared<MyConstraint>(plant, plant_context[i], lb, ub), {q_v[i], qddot[i]}); } } You could refer to the class CentroidalMomentumConstraint on how to construct your own MyConstraint class.
73,880,812
73,895,305
C++ version in .vcxproj files
Is this possible to fetch project's standard of C++ language from .vcxproj files without opening Visual Studio and manually checking it?
I can not add comment. So I post answer here. In Visual Studio C++ project, LanguageStandard will not appear if the language standard has not been changed (Default C++14). After specifying the language explicitly and rebuilding the project, You will find LanguageStandard in the .vcxproj file. There should be similar code samples in C#.Good luck!
73,880,878
73,973,261
QT QString to qml string converts with question marks on windows
When I am trying to display text that contains "·" symbol in QML, I am facing a strange behavoiur. If I define the string with this symbol directly in the qml file: ... Text { text: "1 · 2" } Everything displays fine, but when I am trying to get this string from c++: ... Q_INVOKABLE QString brokenStr() { return QString("1 · 2"); } ... Text { text: myQObjectClass.brokenStr() } The "·" symbol is displayed like a question mark, and this happens only on Windows. On macOS and linux it displays correctly. Looks like something going wrong when QString converts to a qml string. Any ideas how to solve this?
As Öö Tiib mentioned, compiler on windows could not read the plain "·" correctly. The workaround was to use QChar(0xb7) instead. Final solution is returning QString("1 %1 2").arg(QChar(0xb7)) from cpp function
73,881,018
73,881,148
Passing a lambda to a template function taking a std::function as parameter
I have a template function taking a std::function parameter, the template arguments defining function signature: template<typename... Args> void addController(const char * name, const std::function<bool(Args...)> & func); It works passing a std::function variable: std::function<bool()> foo_func = [this]()->bool {return this->isFoo(); }; addController<>("foo", foo_func); //Works But if I pass the lambda directly, it fails deducing the type: //Fails to compile addController<>("foo", [this]()->bool {return this->isFoo(); }); And using a non template function works: void addControllerNoArg(const char * name, std::function<bool()> func); addControllerNoArg("foo", [this]() {return this->isFoo(); }); //Works I need the <typename... Args> template for unwrapping a variant vector argument tables into the function call. This actually does work in the implementation, the only issue is I can't pass a lambda to addController directly. Minimal example: https://onlinegdb.com/MS1cEreKhk
Way to go is generic callable: template<typename F> void addController(const char* name, F f) You can forward it to your std::function version if needed: template <typename... Args> void addController(const char* name, const std::function<bool(Args...)> & func) { /*..*/ } template <typename F> void addController(const char* name, F f) { addController(name, std::function{f}); // CTAD used, so C++17 required }
73,881,357
73,884,163
How to get std::bind refer the explicit constructor defined in class while providing pointer to class member function as arguement?
I'm using std::bind in my code as shown below: std::bind(&Filter::odometryCallback, filter, std::placeholders::_1, odomTopicName, poseCallbackData, twistCallbackData); The Filter class has explicit constructors defined and hence no default constructors are generated by the compiler (for this class). Now, the above line of code throws error with message "use of deleted function" and mentioning the copy constructor of Filter class. My requirement: How to get &Filter::odometryCallback to be considered/evaluated as pointer of explicitly constructed class instance member function ? Any solutions and detailed explanation would be helpful. Edit: Example code I suppose, most of the code below doesn't make much sense to understand the context. But this is what I have right now. OdomFunc setupOdometryCallback(std::string odomTopicName, EkfFilter& filter) { using namespace RobotLocalization; std::vector<int> updateVec = filter.loadUpdateConfig(odomTopicName); std::vector<int> poseUpdateVec = updateVec; std::fill(poseUpdateVec.begin() + POSITION_V_OFFSET, poseUpdateVec.begin() + POSITION_V_OFFSET + TWIST_SIZE, 0); std::vector<int> twistUpdateVec = updateVec; std::fill(twistUpdateVec.begin() + POSITION_OFFSET, twistUpdateVec.begin() + POSITION_OFFSET + POSE_SIZE, 0); int poseUpdateSum = std::accumulate(poseUpdateVec.begin(), poseUpdateVec.end(), 0); int twistUpdateSum = std::accumulate(twistUpdateVec.begin(), twistUpdateVec.end(), 0); bool differential = false; bool relative = false; bool pose_use_child_frame = false; double poseMahalanobisThresh = std::numeric_limits<double>::max(); double twistMahalanobisThresh = std::numeric_limits<double>::max(); const CallbackData poseCallbackData(odomTopicName + "_pose", poseUpdateVec, poseUpdateSum, differential, relative, pose_use_child_frame, poseMahalanobisThresh); const CallbackData twistCallbackData(odomTopicName + "_twist", twistUpdateVec, twistUpdateSum, false, false, false, twistMahalanobisThresh); return std::bind(&EkfFilter::odometryCallback, filter, std::placeholders::_1, odomTopicName, poseCallbackData, twistCallbackData); } Edit 2: I forgot to paste these code below previously. The above Edit 1 & 2 code are in one .cpp file. setupOdometryCallback(parameters) is a simple static function without any class. using OdomFunc = std::function<void(const nav_msgs::Odometry::ConstPtr&)>; int main(int argc, char** argv) { ros::init(argc, argv, "ekf_node"); ros::NodeHandle nh; ros::NodeHandle nh_priv("~"); std::string odomTopicName = "/husky_velocity_controller/odom"; EkfFilter ekf(nh, nh_priv); ekf.initialize(); auto odomF = setupOdometryCallback(odomTopicName, ekf); }
If you want to std::bind a reference parameter, you need to wrap it in std::reference_wrapper, as bind is an ordinary function, that does lvalue-to-rvalue conversion on it's arguments. std::bind(&Filter::odometryCallback, std::ref(filter), std::placeholders::_1, odomTopicName, poseCallbackData, twistCallbackData);
73,881,526
73,881,712
Equivalent Resistance using integers c++
What am I trying to do? I am trying to calculate the equivalent resistance of this resistance setup: R1, R2, R3, R4 are of type int given by the user. The computer should compute the equivalent resistance Req of type int rounding it to the nearest integer. What have I tried? I have tried rounding using the ceil function for rounding. #include <iostream> #include <cmath> int main(){ double R1, R2, R3, R4; std::cout << "enter R1: " << std::endl; std::cin >> R1; std::cout << "enter R2: " << std::endl; std::cin >> R2; std::cout << "enter R3: " << std::endl; std::cin >> R3; std::cout << "enter R4: " << std::endl; std::cin >> R4; double R12; R12 = R1 + R2; double R34; R34 = R3 + R4; int Req; Req = ceil((R12*R34)/(R12+R34)); std::cout << "the equivalent resistance is: " << Req << std::endl; return 0; } What's the issue? I wanted to try doing it without using double type variables, but if I turn R12 and R34 into int, then ceil doesn't work anymore. Why isn't this question a duplicate? I only found questions similar to this one but they all have a major drawback: Int overflowing, which in my case is likely to happen in case the resistance is entered in mOhm, so to speak.
To do it with integer types you have to go through two steps. First, do the division. Second, check the remainder to see whether the truncated result needs to be adjusted. int result = (R12 * R34) / (R12 + R34); int rem = (R12 * R34) % (R12 + R34); if (2 * rem >= R12 + R34) ++result; If you write code like that in a real-world project, expect to get funny looks from your co-workers.
73,881,936
73,894,490
How to separate monochromatic objects of different sizes in opencv
I want to separate a noiseless 1-bit (black and white) image with white circles based on the concave part of the outline. Please refer to the picture below. This is the white object to separate: The target result is: Here is my implementation with the watershed algorithm: The above result is not what I want. If the size of the separated objects is similar, my algorithm is fine, but if the size difference is large, a problem occurs as shown in the picture above. I would like to implement an opencv algorithm that can segment a region like the second picture. However, the input photo is not necessarily a perfect circle. It can be oval like the picture below: Or it can be squished: However, I would like to separate it based on the concave part of the outline anyway. I think it can be implemented by using the distanceTransform function well, but I'm not sure how to approach it. Please let me know which way to refer. Thank you.
If you want to find the minimal openings, you can use a medial axis based approach. Pseudo code: compute contours of bitmap compute medial-axis of bitmap for each point on medial-axis: get minimal distance d from medial axis algorithm for each local minimum of distance d: get two points on bitmap contours with minimal distance that are at least d apart from each other use these points for deviding line If you need a working implementation in python, please let me know. I would use skimage lib. For other languages you might have to implement medial-axis on your own. But that shouldn't be a big deal.
73,881,963
73,882,682
Understanding libunifex's member_t template metaprogramming facility
I'm currently trying to understand the std::execution proposal by studying libunifex's implementation. The library makes heavy use of template metaprogramming. There's one piece of code I really have trouble understanding: template <class Member, class Self> Member Self::* _memptr(const Self&); template <typename Self, typename Member> using member_t = decltype( (std::declval<Self&&>() .* _memptr<Member>(std::declval<Self&&>()))); What exactly is member_t used for? It's used in the implementation of then: template <typename Sender, typename Receiver> requires std::same_as<std::remove_cvref_t<Sender>, type> && receiver<Receiver> && sender_to<member_t<Sender, Predecessor>, receiver_t<std::remove_cvref_t<Receiver>>> friend auto tag_invoke(tag_t<connect>, Sender&& s, Receiver&& r) noexcept( std::is_nothrow_constructible_v<std::remove_cvref_t<Receiver>, Receiver> && std::is_nothrow_constructible_v<Function, member_t<Sender, Function>> && is_nothrow_connectable_v<member_t<Sender, Predecessor>, receiver_t<std::remove_cvref_t<Receiver>>> // ----------------------^ here ) -> connect_result_t<member_t<Sender, Predecessor>, receiver_t<std::remove_cvref_t<Receiver>>> { /* ... */ }
_memptr is a function declared in such a way that _memptr<Member>(self) will give you a pointer to member of <class type of self> of type Member regardless of self's constness or value category. So if Self is possibly a reference type, Member Self::* would be ill-formed, but decltype(_memptr<Member>(std::declval<Self&&>())) will still give you the type you want. The result of applying std::declval<Self&&>() .* to the member pointer is that it will produce the referenced member with the value category one would expect from a member access expression via . when the left-hand side has the value category indicated by Self's reference-qualification. That means if Self is a lvalue reference the expression will also be a lvalue and if Self is a rvalue reference or a non-reference the result will be a xvalue (rvalue). Applying decltype to the expression gives you correspondingly a lvalue or rvalue reference to the member's type. It tells you whether, given the value category of self as a forwarding reference with template parameter Self its member of type Member should be moved from or instead copied where necessary. Now if you have e.g. template<typename T> void f(T&& t) { auto s = (member_t<T, decltype(t.s)>)(t.s); } where s is a non-reference non-static data member of T, then s will be copy-constructed from t.s if f is passed a lvalue and move-constructed from it if passed a rvalue. Essentially it is std::forward for the member. In your shown code it is not directly used this way, but instead the member's type with correct reference-qualification is passed to some type trait e.g. in std::is_nothrow_constructible_v<Function, member_t<Sender, Function>> to to check whether Function can be (nothrow) constructed from a Function lvalue or rvalue depending on whether or not s was passed a lvalue or rvalue. It think this performs an equivalent action to what std::forward_like in C++23 will do when used as template <typename Self, typename Member> using member_t = decltype(std::forward_like<Self>(std::declval<Member>())); (I would not call that template metaprogramming by the way. Nothing here is using template instantiations to implement some algorithm at compile-time.)
73,882,312
74,170,820
Missing libstdc++ headers for arm-none-eabi on Fedora Linux
I am programming the Raspberry Pi Pico-W and I would like to link against the C++ STL, in order to use some of the Standard Library functionalities and containers. I have found the package on Ubuntu, which I used in a professional development environment and I therefore also wanted to install it on Fedora 36, but found it missing in the official and unofficial repositories. Following packages are available to me currently, so it is really just the libstdc++ that is missing, since the C Library (newlib) is there. arm-none-eabi-binutils-cs.x86_64 arm-none-eabi-gcc-cs.x86_64 arm-none-eabi-gcc-cs-c++.x86_64 arm-none-eabi-newlib.noarch libstdc++.i686 libstdc++.x86_64 libstdc++-devel.x86_64 One option I got recommended was to get the headers manually from arm itself, which also includes the rest of the toolchain. Is there some package I am missing in the Fedora repositories, or is it just really not available as one package?
Fedora does not seem to provide such packages and I have also not been able to find copr repos for that. Therefore the only solution left, was to install directly from arm. This link gives a short guide for those that need it. Additionally, since I am using NeoVim with its built-in lsp, I need to add a flag to the clangd configuration, namely --query-driver=/*/*/bin/*gcc, which globs for the compiler found in the compile commands. But this only as a side note. After that everything seems to work as one would expect.
73,882,720
73,883,549
couldn't infer template argument - do I need to use explicit template parameters?
template <int I, typename T> struct Wrap { T internal; }; template <int I, typename T> Wrap<I, T> DoStuff(int z) { return Wrap<I, T>{(T)z}; } class Wrapped { public: // Working Wrap<1, int> GetInt() { return DoStuff<1, int>(1); } Wrap<2, long> GetLong() { return DoStuff<2, long>(2); } // Not working Wrap<3, char> GetChar() { return DoStuff(3); } }; Try it online Why is the third function failing to resolve the template argument? I thought the compiler would try to match the template definition with the return type of the function. Is this working in c++14 or any newer versions?
Deduction doesn't use return value... "Except" for converting operator. So you might create a class which convert to any Wrap<I, T>: struct ToWrap { int n; template <int I, typename T> operator Wrap<I, T>() const { return Wrap<I, T>{T(n)}; } }; ToWrap DoStuff(int z) { return ToWrap{z}; } Demo
73,883,660
73,883,856
Avoiding stack overflow when implementing depth first search in c++
connected components of triangle faces in a mesh I have implemented depth first search using the above link and works fine for most of my data samples. When my data sample is very large, the code reaches a break point, likely to be stack overflow as the recursive function gets too deep. Is there any way to avoid this? or do I have to use some other way like breadth first search / union find algorithm to find connected components in a graph. #include <bits/stdc++.h> using namespace std; class Graph { // A function used by DFS void DFSUtil(int v); public: int count; map<int, bool> visited; map<int, list<int> > adj; // function to add an edge to graph void addEdge(int v, int w); // prints DFS traversal of the complete graph void DFS(); }; void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } void Graph::DFSUtil(int v) { // Mark the current node as visited and print it visited[v] = true; cout << v << " "; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i); } // The function to do DFS traversal. It uses recursive // DFSUtil() void Graph::DFS() { count = 0; // Call the recursive helper function to print DFS // traversal starting from all vertices one by one for (auto i : adj) if (visited[i.first] == false) { DFSUtil(i.first); count++; } } int main() { // Create a graph given in the above diagram Graph g; for face in faces : { g.addEdge(face[0], face[1]); g.addEdge(face[0], face[2]); g.addEdge(face[1], face[0]); g.addEdge(face[1], face[2]); g.addEdge(face[2], face[0]); g.addEdge(face[2], face[1]); } cout << "Following is Depth First Traversal \n"; // Function call g.DFS(); cout << "number of connected components = " << g.count << "\n"; return 0; }
With a recursive algorithm, there is no way to avoid a stack overflow. But, you need to re-implement your algo with an iterative version using a stack. Here is a rough implementation . void Graph::DFSUtil(int v) { stack<int> stack; stack.push(v); cout << v << " "; while (!stack.empty()) { int v = stack.top(); stack.pop(); if (!visited[v]) { cout << v << " "; visited[v] = true; } for (int i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) stack.push(*i); } }
73,883,980
73,884,249
Can't debug 32bit application with gdb and a dynamic loader into remote target arm64
I'm trying to use gdb for debug an application in an arm64 device in a particular situation: -The device is an embedded linux arm64 running linux: $ uname-a Linux HMI-fa93 4.14.78-rt47 #1 SMP PREEMPT RT Fri Apr 29 08:40:42 UTC 2022 aarch64 GNU/Linux I have no problem at all when trying to use gdb with an application that uses native 64 bit (using gdb-multiarch on host and gdbserver aarch64 on target). In this device i have also an application running at 32 bit which is called using this command for execution: /customfolder/lib32/ld-linux-armhf.so.3 --library-path /customfolder/lib32 ./TestGDB32 The application run whitout problems so far but the problem is when i want to debug it using gdb. I've tested a lot of combinations but every time i'm not able to debug the application. I'm afraid that when launching the gdb he think that i'm trying to debug the ld-linux-armhf.so.3 and not my application. I launch the debug in this way: /customfolder/lib32/ld-linux-armhf.so.3 --library-path /customfolder/lib32 /customfolder/bin/gdbserver --once host:10010 /customfolder/lib32/ld-linux-armhf.so.3 --library-path /customfolder/lib32 ./TestGDB32 Basically i'm trying to run gdb at 32 bit and launching the debug of the 32 bit application. The output on the host is like that: 0xf7fbea80 in ?? () (gdb) list No symbol table is loaded. Use the "file" command. (gdb) bt #0 0xf7fbea80 in ?? () #1 0x00000000 in ?? () Backtrace stopped: previous frame identical to this frame (corrupt stack?) How can i debug an application at 32bit that runs with this dynamic loader using gdb?
I launch the debug in this way Yes, when you launch the app this way, GDB will think that you are running ld-linux-armhf.so.3, and debugging will be very difficult. It is possible to debug the app launched that way -- you would need to figure out where the main binary (assuming it's PIE) and all the shared libraries are loaded, and use add-symbol-file for each one, but a much easier solution is to simply build the application so it references desired loader (-Wl,--dynamic-linker=/customfolder/lib32/ld-linux-armhf.so.3) and has desired RPATH (-rpath=/customfolder/lib32), and launch it "normally" (./TestGDB32). If you do that, debugging should just work™.
73,884,235
73,885,214
How to use C++ library in Vala
I want to use vega library for working on dicom files. Sample code from its website is as follows: #include <string> #include "vega/dictionary/dictionary.h" #include "vega/dicom/file.h" int main() { // Set the dictionary file vega::dictionary::Dictionary::set_dictionary("/path/to/dictionary/dictionary.txt"); // Read the DICOM file in const std::string file_name = "/path/to/dicom/file/dicom.dcm"; vega::dicom::File file(file_name); // Print a human-friendly representation of the file to std::cout vega::Formatter formatter(std::cout); file.data_set()->log(formatter); } This page explains including C code, but what about C++ code? This official page states that "If the library is written in C++, you cannot bind it to Vala unless there is a separate C binding of the C++ library (e.g., LLVM). ". Hence, it seems to me that I cannot use vega library. Am I correct? Edit: Also, will valabind / valabind-cc with swig help?
Yes, that would be correct, I believe. You can only link a C library, without namespaces and whatnot. To use your C++ library in Vala, I would say you have to either have to either a) rewrite everything in C, but this is obviously lots of work, so very undesirable, or b) find a version of your library written in plain C. As for creating a wrapper, you would have to expose the C api from C++. This question's answers can help with that. Note that this would probably include editing the source code of the library, which may be unavailable or restricted based on the license of the library. I don't believe, as does @wohlstad, that you are unable to use a plain C++ library in Vala without the C api.
73,884,580
73,884,866
Sfml lostFocus / gainedFocus cpu usage
Why when I run this simple code and just doing nothing CPU usage by this app is around 0.4% #include <SFML/Graphics.hpp> int main() { sf::RenderWindow window(sf::VideoMode(800, 800), "hi", sf::Style::Close | sf::Style::Titlebar); window.setFramerateLimit(60); sf::Event event; bool lostFocus = false; while (window.isOpen()) { while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); else if (event.type == sf::Event::LostFocus) lostFocus = true; else if (event.type == sf::Event::GainedFocus) lostFocus = false; } if (!lostFocus) { window.clear(sf::Color::White); window.display(); } } } But when I click on other app, CPU usage by this app increases to 12%. Does GainedFocus actually eat so much cpu power or what? (I just wanted to make a simple pause of game and saw this cpu usage)
As already mentioned, when your window doesn't have focus and you're not updating the window, the loop goes into a hot spin where it's continuously checking for events. When you've lost focus, you instead want to block and wait for a GainedFocus event to occur. As a very simple example, you could do something like void block_until_gained_focus(sf::Window& window) { sf::Event event; while (true) { if (window.waitEvent(event) && event.type == sf::Event::GainedFocus) { return; } } } Then your main game loop could look something like while (window.isOpen()) { while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); else if (event.type == sf::Event::LostFocus) wait_until_gained_focus(window); } window.clear(sf::Color::White); window.display(); } Now if you wanted to do additional work while focus is lost you'll need a different implementation, but the key here is to use waitEvent instead of pollEvent.
73,884,830
73,884,932
Accessing private member of base class using derived class member function
I have just started learning about inheritance and I know that private members of base class are not inherited by the derived class. But when I run the 'get_data1' function of the derived class, it returns the value of data1 from the base class even though I have defined a new 'data1' in the derived class. So shouldn't it return 3 instead of 5 as it is a member function of the derived class? class base { int data1; public: base() { data1=5; } int get_data1() { return data1; } }; class derived : public base { int data1; public: derived() { data1=3; } void printData() { cout<<get_data1()<<endl; } }; int main() { derived der1; der1.printData(); return 0; }
I know that private members of base class are not inherited by the derived class. No, private members are inherited just like other members. The difference is that they're not accessible from the derived class unlike public or protected members. shouldn't it return 3 instead of 5 as it is a member function of the derived class? No, you're confusing calling printData with calling getdata1. Even though printData is a derived class member function, it calls the base class' base::get_data1 member function which prints the base class' data member and hence the output. See the added comments in the below program. class base { int data1; public: base() { data1=5; } int get_data1() { return data1; //this prints base class' data1's value } }; class derived : public base { int data1; public: derived() { data1=3; } void printData() { cout<<get_data1()<<endl; //this calls base class' base::get_data1() } }; int main() { derived der1; der1.printData(); //this calls derived class' derived::printData() return 0; }
73,885,177
73,885,398
Why can't I use 'delete' for this line?
I've started to learn linked lists today, and I am trying to delete nodes. void deleteEnd(Node* refNode) { Node* lastNode; lastNode = new Node; while((refNode->next)->next != NULL) { refNode = refNode->next; } lastNode = refNode->next; refNode->next = NULL; delete lastNode; } void deleteIndex(Node* refNode, int index) { Node *prev, *next, *deleted; prev = new Node; next = new Node; deleted = new Node; for(int i=1; i < index; i++) { refNode = refNode->next; } prev = refNode; deleted = prev->next; next = deleted->next; prev->next = next; free(deleted); } I can use delete in the first one, but when I try to use it in the second, it doesn't work. The terminal doesn't give any error messages. I found some information on the Internet, but I couldn't really understand it. This is my linked list: class Node { public: int data; Node *next; };
As pointed out by the comments, there are several things wrong with this code. All issues are from the comments, none are found by me, all credit goes to François Andrieux, Jesper Juhl, Sven Nilsonn, Avi Berger, and Thomas Matthews. First, the code probably doesn't work because you mixed new and free. new is a C++ API function, while free is from C. Whenever you construct an object with new, which should not be that often with C++'s automatic memory management, you must free it with delete. Second, when looping through a list, always start at 0. The only reason otherwise would be to start at the second item. Third, in this passage: prev = new Node; ... prev = refNode; ... prev->next = next; When you set prev, it is overwriting the previous value. If this is a pointer, as it is, then this causes a memory leak. Always delete it before overwriting. Finally, in deleteEnd, as pointed out by Thomas Matthews, you are trying to dereference, or get the value from, the pointers, without checking if it is nullptr. If one is, it will cause undefined behavior, and can crash the program.
73,886,229
73,886,670
Templated sub-class with `std::string`-to-`T` conversion in virtual function
I have a sub-class that has to implement a virtual function so that callers can interface with it without knowing its concrete type. But I'd like to template this sub-class to work with different types. Basically, this: class Base { public: virtual void insert(const std::string & val, const std::string & type_str) = 0; }; template<typename T> class C : public Base { public: virtual void insert(const std::string & val, const std::string & type_str) final { // Something that tries to convert val to type T and inserts into container; // Would throw if conversion fails // e.g.: if (type_str == "int") container.insert(std::stoi(val)); else if (type_str == "str") container.insert(val); // Error: No matching function call to `insert` [...] } private: std::set<T> container; }; I understand the problem: any given specialization of C won't have a container that accepts types other than T; it's only a runtime assurance that nobody calls C::insert() with the wrong type. Is there any way around this? I'd like to keep the same interface for this sub-class as I have with others that inherit from Base, which requires accepting a string and doing the conversion internally. More than happy to have a C++20 solution (had some failed attempts using concepts to solve this...). And if it matters, I'm using gcc.
You can use if constexpr (C++17 and later): #include <type_traits> class Base { public: virtual void insert(const std::string & val, const std::string & type_str) = 0; }; template<typename T> class C : public Base { public: virtual void insert(const std::string & val, const std::string & type_str) final { if constexpr(std::is_same_v<T,int>){ assert(type_str == "int"); // or you can just drop this, depend on what you want container.insert(std::stoi(val)); } else if constexpr(std::is_same_v<T,std::string>){ assert(type_str == "str"); container.insert(val); } else{ static_assert(!std::is_same_v<T,T>,"not supported conversion"); } } private: std::set<T> container; }; Or, you can use template specialization instead.
73,886,251
73,886,808
C++ input/output queue for multiple input source
I have a task that requires listening to multiple data source, and process the data to calculate some statistics (like cumulative sum of all data) for every new record coming in. I am reading this post for a queue with condition variables. I wonder if this solution will work for multiple input scenario. Say we have two listener thread A & B, and one consumer thread. Listener A calls the push function, gains and releases the lock, then notify the consumer with condition variable. Is it possible that Listener B will take over immediately as it has received data in the meantime, stopping the consumer from processing the new data introduced by A? How can one make sure that the consumer logic has ran exactly once whenever new data comes in, regardless of which listener it comes from?
Yes, but what is the the problem? Producer A (we call them producers) will lock, add an item to the queue, notify, unlock (or in some versions - not in C++ - unlock and then notify). Producer B will lock, add an item, notify, unlock. The consumer will wake up, lock, check the queue, get an item, unlock, and process the item. Then the consumer will lock, check the queue before waiting again and it will see there is already an item there so it will not wait. It will get the item and unlock. When using condition variables, it is important that you check if the thing you are waiting for has already happened before you wait.
73,886,685
73,891,668
Segmentation Fault when working with argv C++
I have until now: int main(int argc, char * argv[]) { std::vector<std::string> args; for (int i = 1; i < argc; i++) { args.push_back({ argv[i] }); } std::string dateString = args[1]; return 0; } and I get Segmentation Fault on line: std::string dateString = args[1]; What I want to do is to use something like: ./myalgorithm.cpp 2022-09-01 where 2022-09-01 is a date. Then, I want to get to this date via argv[1], save it to a std::string variable and then do some computation with each value from the date( 2022, 09 and 01). I was thinking to save this date to a string and then with the use of string.substr(...) to save into int variables the numbers from the date: int year = stoi(mystring.substr(0,4)); int month = stoi(mystring.substr(6,2)); int day = stoi(mystring.substr(9,2)); EDIT: I edited my code and it works: int main(int argc, char * argv[]) { std::vector<std::string> args; for (int i = 1; i < argc; i++) { args.push_back({ argv[i] }); } for (auto dateString: args) { double year = stoi(dateString.substr(0,4)); double month = stoi(dateString.substr(5,2)); double day = stoi(dateString.substr(8,2)); std::cout << year << std::endl; std::cout << month << std::endl; std::cout << day << std::endl; } return 0; } But I don't understand why do I need to write: std::vector<std::string> args; for (int i = 1; i < argc; i++) { args.push_back({ argv[i] }); } Instead of simply: std::vector<std::string> args; args.push_back({ argv[1] }); EDIT: Corrected Code: int main(int argc, char * argv[]) { std::vector<std::string> args; if (argc > 1){ args.push_back({ argv[1] }); } for (auto dateString: args) { int year = stoi(dateString.substr(0,4)); int month = stoi(dateString.substr(5,2)); int day = stoi(dateString.substr(8,2)); int gpsweek = GPSweek(year, month, day); printf("%d\n", gpsweek); } return 0; }
When you use ./myalgorithm.cpp 2022-09-01, what are argc and argv? argc is count of arguments + program name. argv is program name and these arguments. So argc = 2 and argv = { myalgorithm.cpp, 2022-09-01 } std::vector<std::string> args; for (int i = 1; i < argc; i++) { args.push_back({ argv[i] }); } After the code, the variable args is { "2022-09-01" } because you start from i = 1 but not 0. C++ array (including std::vector) index starts from 0, so the first item has index being 0. If you try to take the second item with index = 1 then it is the array out of bounds. It is Undefined Behavior in C++ and Segmentation Fault is one of the outcomes. Use args[0] to take the first item - "2022-09-01". The range based for uses iterators which start from index = 0 for std::vector, therefore your correct code works.
73,886,997
73,887,121
Was a new constructor added to std::string in c++23 that accepts std::array<char, N>?
Recently a bug was discovered in our code where we were accidentally converting a std::array<char, N> to std::string. The buggy code doesn't compile in c++20 mode but compiles and //mostly// works in c++23 mode except for some edge cases with null termination. I'm using gcc 11.1. #include <iostream> #include <string> #include <array> int main() { std::array<char, 3> x = {'a', 'b', '\0'}; std::string s(x); std::cout << "'" << s << "'" << " has length " << s.size() << std::endl; //outputs "'ab' has length 3" } I suspect this may be related to P1989R2 - Range constructor for std::basic_string_view but I don't know what to make of it. Is it a bug or just a weird behavior or what?
Yes, it is related to P1989. One of std::string's constructors is: template< class StringViewLike > explicit constexpr basic_string( const StringViewLike& t, const Allocator& alloc = Allocator() ); which is constrained on StringViewLike being convertible to std::string_view. P1989 added this constructor to std::string_view: template <class R> requires /* ... */ constexpr string_view(R&&); The constraints there require R to be a contiguous_range with appropriate value type and a few other things. Importantly, std::array<char, N> meets those requirements, and this constructor is not explicit. As a result, you can now construct a std::string from a std::array<char, N>. This led to P2499 (string_view range constructor should be explicit), which suggested what the title says, and P2516 (string_view is implicitly convertible from what?), which suggested removing the constructor entirely. In the end, the decision was to make the constructor explicit rather than removing it entirely (or keeping it implicit): template< class R > explicit constexpr basic_string_view( R&& r ); Because the string constructor from StringViewLike is constrained on convertible to (which requires implicit construction), this means std::string is no longer constructible from std::array<char, N> (or std::vector<char> or ... ).
73,887,205
73,922,663
__static_initialization_and_destruction_0 seg fault
I was developing a C++ program and everything was working fine. Then, while I was programming, I ran make and ran my program like usual. But during the execution of it all, my computer crashed and shut itself off. I reopened my computer and ran make again but this time it gave me a bunch of errors. Everything seemed off, like my whole computer is corrupted. But everything was working as intended in my operating system except the stuff related to my program. I've tried making a new c++ project, it works just fine. I've tried deleting the project and re-compiling it from github to no avail. I managed to compile the program in the end but now it gives me a seg fault. The first thing my program does is to print out Starting... to the screen, but this segfault occurs without ever printing that, so it led me to believe that this error is linker related. (Even when the make command was failing, before I fixed it, it told me there was a linker error) Here is what valgrind says: turgut@turgut-N56VZ:~/Desktop/CppProjects/videoo-render$ valgrind bin/Renderer ==7521== Memcheck, a memory error detector ==7521== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. ==7521== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info ==7521== Command: bin/Renderer ==7521== ==7521== Invalid read of size 1 ==7521== at 0x484FBD4: strcmp (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==7521== by 0x121377: __static_initialization_and_destruction_0 (OpenGLRenderer.cpp:111) ==7521== by 0x121377: _GLOBAL__sub_I__ZN6OpenGL7Texture5max_zE (OpenGLRenderer.cpp:197) ==7521== by 0x659FEBA: call_init (libc-start.c:145) ==7521== by 0x659FEBA: __libc_start_main@@GLIBC_2.34 (libc-start.c:379) ==7521== by 0x1216A4: (below main) (in /home/turgut/Desktop/CppProjects/videoo-render/bin/Renderer) ==7521== Address 0x0 is not stack'd, malloc'd or (recently) free'd ==7521== ==7521== ==7521== Process terminating with default action of signal 11 (SIGSEGV) ==7521== Access not within mapped region at address 0x0 ==7521== at 0x484FBD4: strcmp (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so) ==7521== by 0x121377: __static_initialization_and_destruction_0 (OpenGLRenderer.cpp:111) ==7521== by 0x121377: _GLOBAL__sub_I__ZN6OpenGL7Texture5max_zE (OpenGLRenderer.cpp:197) ==7521== by 0x659FEBA: call_init (libc-start.c:145) ==7521== by 0x659FEBA: __libc_start_main@@GLIBC_2.34 (libc-start.c:379) ==7521== by 0x1216A4: (below main) (in /home/turgut/Desktop/CppProjects/videoo-render/bin/Renderer) ==7521== If you believe this happened as a result of a stack ==7521== overflow in your program's main thread (unlikely but ==7521== possible), you can try to increase the size of the ==7521== main thread stack using the --main-stacksize= flag. ==7521== The main thread stack size used in this run was 8388608. ==7521== ==7521== HEAP SUMMARY: ==7521== in use at exit: 72,741 bytes in 3 blocks ==7521== total heap usage: 3 allocs, 0 frees, 72,741 bytes allocated ==7521== ==7521== LEAK SUMMARY: ==7521== definitely lost: 0 bytes in 0 blocks ==7521== indirectly lost: 0 bytes in 0 blocks ==7521== possibly lost: 0 bytes in 0 blocks ==7521== still reachable: 72,741 bytes in 3 blocks ==7521== suppressed: 0 bytes in 0 blocks ==7521== Rerun with --leak-check=full to see details of leaked memory ==7521== ==7521== For lists of detected and suppressed errors, rerun with: -s ==7521== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0) Segmentation fault (core dumped) turgut@turgut-N56VZ:~/Desktop/Cpp OpenGLRenderer.cpp:197 is just the end of the file and here is what's writeen in OpenGLRenderer.cpp:111: static bool __debug = strcmp(getenv("DEBUG"), "true") == 0; It says that there is an error with strcmp but I've tried using that function on a different project and it worked just fine. What could be the reason for this? I'm on ubuntu 22.04, gcc verison 11.2.0.
this segfault occurs without ever printing that, so it led me to believe that this error is linker related. The linker is not involved in your program running, so it can't be "linker related". There is a dynamic loader (if your program uses shared libraries), so perhaps that's what you meant. In any case, the crash is happening because OpenGLRenderer.cpp:111 (probably in libGL.so) is calling strcmp() with one of the arguments being NULL (which is not a valid thing to do). This does happen before main. This line: static bool __debug = strcmp(getenv("DEBUG"), "true") == 0; is buggy: it will crash when DEBUG is not set in the environment (getenv("DEBUG") will return NULL in that case). As a workaround, you can run export DEBUG=off, before running your program and the crash will go away. It's unclear whether you inserted this line into OpenGLRenderer.cpp yourself or whether it was already present, but it's buggy either way. P.S. A correct way to initialize __debug could be: static const char *debug_str = getenv("DEBUG"); static const bool debug = strcmp(debug_str == NULL ? "off" : debug_str, "true") == 0; P.P.S. Avoid using identifiers prefixed with __ (such as __debug) -- they are reserved.
73,887,477
73,887,516
Can someone explain the syntax behind this line of code? C++
My professor is having us change her functions to work for her assignment on Binary Search Trees. I know that this line she has assigns myHeight to whatever value being compared that is greater, but I have no idea how it's actually doing that. int maxH = (hL > hR) ? hL : hR; I want to use this in the future since it can save time writing code, but to do that I need to understand the syntax first. Thanks guys
This is the so called "conditional operator" in c++. It works as follows: the expression before the ? is evaluated and converted to bool, if it evaluates to true, the second operand is evaluated (i.e. hL in your example), otherwise, the third operand (hR in your example) is evaluated. The result is assigned to maxH. See here for more detail (go down to the section "Conditional operator").
73,887,705
73,887,750
fields use to implement hash and comparison functions in unordered_map
Is it necessary for the comparison and the hash function of a custom type in an std::unordered_map to use the same set of fields? (i.e) given: struct Foo { int i; float f; }; If I generate hashes only using i but use both i and f to implement equality, will I run afoul of anything? In my understanding, the comparison function is used to determine the relative ordering of objects within a bucket. So I don't think there should be a problem but I am not 100% sure.
That's fine, all that is required is that x == y implies hash(x) == hash(y) which your scheme does.
73,888,449
73,888,740
C++ Complex number expression for integrating
I'm trying to implement Monte-Carlo method to solve an integral and can't figure an approximation for my function. double function(double x) { std::complex<double> fz = (pow(-7 * pow(x, 4) - 3 * x + 11, 1.0/3.0) / pow(-2 * pow(x, 6) - 14 * x - 8, 1.0/4.0)); cout << fz << endl; double f = fabs(fz); return f; } When I substitute 0.25, the approximate result has to be 0.83 - 0.83i (using online calculators) But in my C++ code, it results in 1. What did I do wrong? The code for approximation: double integral(unsigned int N) { double sum{}, randomNumber; for (unsigned int i = 0; i < N; i++) { randomNumber = static_cast<double>(rand()) / static_cast<double>(RAND_MAX) / 3; sum += function(randomNumber); // estimate function with random value [0; 3] } return (3 * sum / N); }
The problem was with std::pow function. To apply it to complex numbers, the first argument of it must be of complex type: std::complex<double> numerator(-7 * pow(x, 4) - (3 * x) + 11); std::complex<double> denumerator(-2 * pow(x, 6) - (14 * x) - 8); std::complex<double> fz = pow(numerator, third) / pow(denumerator, quarter);
73,888,694
73,888,772
decltype does not preserve ref qualifier from structured binding
Usually decltype perseveres the ref qualifiers auto a = 0; auto& a_ref = a; static_assert(std::is_reference_v<decltype(a_ref)>); But apparently not when it's argument is obtained from structured binding auto p = std::pair{1, 2.f}; auto& [i, d] = p; static_assert(std::is_reference_v<decltype(i)>); // fails https://godbolt.org/z/qWT574fr9 I'm pretty sure that i and d are references here. They should be according to oldnewthing and intellisense is telling me so.
Looks like this is how it is supposed to be: decltype(x), where x denotes a structured binding, names the referenced type of that structured binding. In the tuple-like case, this is the type returned by std::tuple_element, which may not be a reference even though a hidden reference is always introduced in this case. From cpprefence In your case, you are using a pair, but i am pretty sure this falls under tuple like type.
73,889,051
73,889,161
std::initializer_list rvalue/literal as parameter of (variadic) template
Please help me to understand why a std::initializer_list literal can't be deduced as a template parameter? AFAIK, there's no notion of an init-list literal in the language yet, but then why/how does this work? auto il = { 1, 2, 3, 4, 5 }; Here is my code: import <iostream>; import <string>; import <vector>; template <typename T> constexpr auto type_name() { std::string_view name, prefix, suffix; #ifdef __clang__ name = __PRETTY_FUNCTION__; prefix = "auto type_name() [T = "; suffix = "]"; #elif defined(__GNUC__) name = __PRETTY_FUNCTION__; prefix = "constexpr auto type_name() [with T = "; suffix = "]"; #elif defined(_MSC_VER) name = __FUNCSIG__; prefix = "auto __cdecl type_name<"; suffix = ">(void)"; #endif name.remove_prefix(prefix.size()); name.remove_suffix(suffix.size()); return name; } template< typename T > int SAI_BF_helper(T&&) { return 0; } int SAI_BF_helper(int i) { return i; } // function that take any number parameters of any type and then return sum of all ints using binary left folding expressions template< typename ... Types > ¡int SumAllInts_BinaryLeftFold(Types ... args) { return (0 + ... + SAI_BF_helper(args)); } template< typename T > void PrintTypeName(T&& t) { std::cout << type_name< decltype( std::forward< T >(t) )> () << std::endl; } // if this overload is removed then 'PrintTypeName({1,2,3});' code will not compile template< typename T > void PrintTypeName( std::initializer_list< T >&& t) { std::cout << type_name< decltype(std::forward< std::initializer_list< T > >(t))>() << std::endl; } int main() { std::vector< int > numbers{ 1, 2, 3 }; auto il = { 1, 2, 3, 4, 5 }; PrintTypeName(numbers); // output: class std::vector<int,class std::allocator<int> >& PrintTypeName(il); // output: class std::initializer_list<int>& PrintTypeName({1,2,3}); // output: class std::initializer_list<int>&& std::cout << SumAllInts_BinaryLeftFold() << std::endl; // 0 std::cout << SumAllInts_BinaryLeftFold("", 0, 1, 2.2, 'a', "char*", 10, std::string("str"), numbers, il) << std::endl; // 11 //std::cout << SumAllInts_BinaryLeftFold( 1, {1, 2}) << std::endl; // MSVC error message: 'initializer list': is not a valid template argument for 'Types' }
The short answer: initializer lists (the language mechanic, not the type) are magic. No, really. The C++ standard has explicit wording for initializer-list syntax to produce a std::initializer_list object in certain circumstances such as constructing an auto-parameter, but an initializer list expression is not itself always a std::initializer_list; it depends on the circumstances. This distinction is needed because the same syntax may be used in place of implicit construction for cases like parameters. For example, consider the following code: auto do_something(Person) -> void; ... do_something({}); // Calls Person() -- not Person(std::initializer_list<U>) In this, {} isn't meant to be a std::initializer_list object; it's an implicit default-construction of Person. Because these cases exist, deducing the exact type of a brace-enclosed initializer list is not so straight-forward. For example: template <typename T> auto do_something(T) -> void; do_something({1}) -> void; In the above case, what should T be? Is it do_something<std::initializer_list<int>>? do_something<int> with int{1}? What if this were {1, 2U}? It can get complicated.
73,889,446
73,889,544
Is there an advantage of using parentheses in decltype over explicitly typing const ref
Which is better: decltype((foo)) x = bar; const decltype(foo)& x = bar; If these are just two ways of saying the same thing, why are the parentheses even part of the language?
If you want to declare "a reference to the same type of object as foo", then I would prefer the second option. That's not really what the other form of decltype is for. The decltype keyword pulls double-duty: It tells you the type of a variable It tells you the type and value category of an expression That's what the extra parenthesis do. foo is an identifier, so decltype(foo) will tell you the type of the object identified by that identifier. (foo) is not an identifier; it is an expression, so decltype((foo)) will tell you both the type and value category of it. It returns an lvalue-reference for an lvalue expression, an rvalue-reference for an xvalue, and a non-reference type for a prvalue. For example: int i = 10; using A = decltype(i); // A is an alias for int // because i is an identifer using B = decltype((i)); // B is an alias for int& // because (i) is an lvalue expression using C = decltype(std::move(i)); // C is an alias for int&& // because std::move(i) is an xvalue // expression using D = decltype(i + 1); // D is an alias for int // because i + 1 is a prvalue expression Demo The value categories of all of the expressions in that example are obvious from looking at them, but consider a template: template <typename Func> void foo(Func func) { func(42); } The expression func(42) could result in any value category, depending on the exact return type. That's where the expression form of decltype becomes useful.
73,889,608
73,891,209
How to detect a CMenu visiable or not in MFC?
I'm making a right click menu in my application. And I want to check whether the menu is shown or not. But I read the Microsoft docs of CMenu and found that there is no way to make it. How to get the menu state, and is there any way to get the menu disappear event?
The system sends a WM_ENTERMENULOOP message to a menu's owner window whenever a menu is about to be shown, and a WM_EXITMENULOOP message after it has been dismissed. Those messages map to the CWnd::OnEnterMenuLoop and CWnd::OnExitMenuLoop message handlers that your code can override to keep track of the menu state. The bIsTrackPopupMenu argument is set to TRUE for a popup menu.
73,890,249
73,891,111
I have a question about the paramether of GetPriorityClass Function (and [in] attribute)
DWORD GetPriorityClass( [in] HANDLE hProcess ); In the documentation they says if the function succeeds, the return value is the priority class of the specified process. The parameter takes [in] HANDLE hProcess that will be the process that i will be take the priority, but i dont know what means [in] or if i have to put some data into the parameter. The docs says the next thing : [in] hProcess A handle to the process. But doesnt explain or show some example or how can i fill the param.
As you can see in the documentation, GetPriorityClass: Retrieves the priority class for the specified process. (emphasis is mine) The handle to the process is passed as the hProcess input argument (marked with the [in] attribute) to the function. This just means you have to supply it yourself. Something like: HANDLE hMyProcess = ...; DWORD dwRes = GetPriorityClass(hMyProcess); if (dwRes == 0) { // Handle error } else { // Use the priority class in dwRes } Notes: More info about [in] attribute here: SAL documentation and here: IDL documentation. SAL is Microsoft's source-code annotation language which uses the _In_ style for this attribute. IDL is the interface definition language which uses the [in] style. But the idea is the same. BTW the current Windows SDK headers use the SAL style. A complete example showing the usage of GetPriorityClass (among other functions): example.
73,891,476
73,893,800
change optimal base of radix/counting sort?
Im learning to implement radix sort but im having trouble understanding how to change to a base different from the optimal base log(n) on base 10 to 2^log(n), with a floor function on the ln. Im using this code from GeeksForGeeks which tend to follow the CLRS pseudocodes, to learn: // C++ implementation of Radix Sort #include <iostream> using namespace std; // A utility function to get maximum value in arr[] int getMax(int arr[], int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } // A function to do counting sort of arr[] according to // the digit represented by exp. void countSort(int arr[], int n, int exp) { int output[n]; // output array int i, count[10] = { 0 }; // Store count of occurrences in count[] for (i = 0; i < n; i++) count[(arr[i] / exp) % 10]++; // Change count[i] so that count[i] now contains actual // position of this digit in output[] for (i = 1; i < 10; i++) count[i] += count[i - 1]; // Build the output array for (i = n - 1; i >= 0; i--) { output[count[(arr[i] / exp) % 10] - 1] = arr[i]; count[(arr[i] / exp) % 10]--; } // Copy the output array to arr[], so that arr[] now // contains sorted numbers according to current digit for (i = 0; i < n; i++) arr[i] = output[i]; } // The main function to that sorts arr[] of size n using // Radix Sort void radixsort(int arr[], int n) { // Find the maximum number to know number of digits int m = getMax(arr, n); // Do counting sort for every digit. Note that instead // of passing digit number, exp is passed. exp is 10^i // where i is current digit number for (int exp = 1; m / exp > 0; exp *= 10) countSort(arr, n, exp); } // A utility function to print an array void print(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; } // Driver Code int main() { int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call radixsort(arr, n); print(arr, n); return 0; } My main problem is that i dont know what 2^log(n) mean on this function, like i understand how to change it to binary base or hexadecimal base, but how does this base change the algorithm compared to base 10 or any of the other ones? why is this base considered close to the optimal one? And how would i even implement it?
The base is the factor by which you would divide a number repeatedly to identify its digits in that base. For instance when base is 10, and we have the number 12, then we can identify the least significant digit by dividing it by the base, which gives us 1 with remainder 2. That remainder is the least significant digit. Then to get the next digit (in right-to-left sense), we divide the previous quotient again by the base, so in the example we get 0 with remainder 1. This time the digit is 1, and the process stops because the quotient is 0. If we change the base to 2 for analysing the same number 12, then we identify the least significant (binary) digit by applying a division by 2: 12 / 2 = 6, remainder 0 6 / 2 = 3, remainder 0 3 / 2 = 1, remainder 1 1 / 2 = 0, remainder 1 Reading the remainders from bottom to top, we get 1100, which is the binary representation of 12. This is to say that in your algorithm, you can easily change the base to another base by modifying the occurrences of 10 where they appear in % 10, / 10, * 10, or in the number of the "buckets" (the size of the count array). So here is your code altered so that it defines a BASE, and you can just change it to whichever base you like: #define BASE 2 void countSort(int arr[], int n, int exp) { int output[n]; int i, count[BASE] = { 0 }; // The number of buckets is BASE for (i = 0; i < n; i++) count[(arr[i] / exp) % BASE]++; // Division is by BASE for (i = 1; i < BASE; i++) // The number of buckets is BASE count[i] += count[i - 1]; for (i = n - 1; i >= 0; i--) { // Division is by BASE output[count[(arr[i] / exp) % BASE] - 1] = arr[i]; count[(arr[i] / exp) % BASE]--; } for (i = 0; i < n; i++) arr[i] = output[i]; } void radixsort(int arr[], int n) { int m = getMax(arr, n); // Power has BASE as base: for (int exp = 1; m / exp > 0; exp *= BASE) countSort(arr, n, exp); } As to what is most efficient: in terms of time complexity it doesn't make a difference which base you choose. If however there is more information about the input than just that they are integers, then it might be that for certain ranges and distributions of input one base may in practice give faster results than another.
73,891,771
73,891,860
Class template argument deduction using function return type
I want to make a class with a template parameter and a function (also with a template parameter) that returns a class instance. However, for shorter code, I want to omit template parameters when returning the result of class construction. I have no clue how do I call this type of technique and if it is possible. For a better description of my question, the code below is an example that I am ideally seeking. template <typename T> class Class { public: Class() { // Construction }; }; Class<int> Function() { return Class(); // not Class<int>(); } int main() { Class<int> instance = Function(); } Depending on how I apply this type of technique, I may also need to use multiple template parameters. Thank you.
This is not possible. Template types are concrete after compilation, unlike languages like C# where there's metadata so it can allow uncomplete generic types, C++ doesn't. Types like Class<> or Class<int,> are not possible. You could do Class<void> and let template deduction fill the void (pun intended). Or you could template the function itself: template <class TInner> Class<TInner> Function() { return Class<TInner>(); } Best of luck.
73,891,984
73,892,113
GTest pass std::vector as a parameter source
I have a function which reads out all files in a selected directory. std::vector<std::string> getAllFilesInDirectory(const std::string_view strDirectory); Now I'd like to run my tests on each element of that vector. My test fixture is pretty straight forward. class myTestfixture: public ::testing::TestWithParam<std::string> { public: myTestfixture(); ~myTestfixture() override; }; Now I'd like to pass each element of the vector to my tests. I know I can pass single explicit values to :testing::Values, but passing a stl container does not work. INSTANTIATE_TEST_CASE_P( myTest, myTestfixture, ::testing::Values( getAllFilesInDirectory("myDir") )); TEST_P(myTestfixture, ValidTest) { //test something } Is it even possible to pass containers as a parameter source to gtest?
You have almost done it but with a small mistake. Try to use ValuesIn() instead of Values(). INSTANTIATE_TEST_CASE_P( myTest, myTestfixture, ::testing::ValuesIn( getAllFilesInDirectory("myDir") ));
73,893,154
73,893,342
Decay std::array to pointer
I have class like this: struct S{ void method1(int *a){ // use a } void method2(int *a){ // use a } }; To avoid allocation, I am doing following: std::array<int, 100> a; S s; s.method1(a.data()); However much nicer will be if I can able to do, without making all methods templates. std::array<int, 100> a; S s; s.method1(a); In C++20 I can use std::span, but currently I want to avoid it as well. Any easy way to define some operator that will be able to convert / cast, but only inside the class?
You can use non-member std::data and call it like s.method1(std::data(a));. That works for raw arrays, std::array, std::span and others.
73,893,180
73,904,508
Pass JS function to C++ as function parameter
I want to make async call to C++ native function, but have some problems: when I call native function in async block (in Promise, exactly), it blocks UI thread and no async call is made. I want to pass callback to C++ function and call it. How can I pass function object? class frame : public sciter::window { public: frame() : window(SW_TITLEBAR | SW_RESIZEABLE | SW_CONTROLS | SW_MAIN | SW_ENABLE_DEBUG) {} void assertion(const std::string& val) { stream << std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count() << ' ' << val << '\n'; stream.flush(); } void asyncFunction(::sciter::value callback) { std::thread{ [callback]() { std::this_thread::sleep_for(std::chrono::milliseconds(5000)); // if I use it in same thread, it blocks UI thread and no async call is made // call callback function } }.detach(); } SOM_PASSPORT_BEGIN(frame) SOM_FUNCS( SOM_FUNC(assertion), SOM_FUNC(asyncFunction) ) SOM_PASSPORT_END private: std::ofstream stream{ "log.txt" }; }; In this implementation I use another thread to make a logic. But if I want to return values (or notify, that call has completed), I need fire event (what I don't want to do, because logic will be spread on whole code) or call some sort of callback. sciter::value have methods is_function_object and is_function, so, probably, I have opportinuty to cast value to the C++ function object. But how can I do this? <html> <head> <title>Test</title> </head> <body> <button #test>Assert</button> <script> function sleep(time) { return new Promise(resolve => { Window.this.frame.asyncFunction(function (result) { Window.this.frame.assertion(result); resolve(result); }); // resolve(Window.this.frame.asyncFunction()) blocks code execution until asyncFunction returns }); } async function answer() { Window.this.frame.assertion("sleep start"); await sleep(5000); Window.this.frame.assertion("sleep end"); return 50; } document.$("button#test").onclick = function () { var p = answer(); p.then(result => { Window.this.frame.assertion("Ended: " + result) }); Window.this.frame.assertion("go next"); } </script> </body> </html>
Well, here are a few possibilities: we can use callback.call() if a function or function object was passed or just return Promise like object. Examples: void asyncFunction(::sciter::value callback) { std::thread{ [callback]() { std::this_thread::sleep_for(std::chrono::milliseconds(5000)); sciter::value result = sciter::value(42); callback.call(result); // invoke the callback function. } }.detach(); } That's how to call callback function. But we can simply return Promise like object (defined here): sciter::value nativeAsyncFunction(int milliseconds) { sciter::om::hasset<NativePromise> promise = new NativePromise(); std::thread([=]() { std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); promise->resolve(42); }).detach(); return sciter::value::wrap_asset(promise); } In this case we don't need to create additional functions like sleep, we just call nativeAsyncFunction in answer and await its result.
73,894,166
73,896,952
Why do profilers fail to get information from my program?
I am trying to profile a C++ program but whenever I run a profiler I get no information even though the debug information works as I can run a debugger on it. I tried using AMD uProf, Very Sleepy and Visual Studio but all of them give me no information. No functions get detected. The program is compiled using clang-cl and runs for only a few milliseconds.
It seems like Windows Defender was messing with somethings, it has caused me some trouble in the past as well. Disabling it and rebooting seems to have fixed the problem. Also due to the program having such a short execution time most profilers aren't able to get enough samples
73,894,292
73,896,155
Plot Histogram from vector data in C++
I'm trying to do a simple task. Draw an Histogram in C++, I'm reading data from a audio file and stored the counted values in a vector. wav_hist.h class WAVHist { private: std::vector<std::map<short, size_t>> counts; public: WAVHist(const SndfileHandle& sfh) { counts.resize(sfh.channels()); } // Mono channel WAVHist() { counts.resize(1); } void update(const std::vector<short>& samples) { size_t n { }; for(auto s : samples) counts[n++ % counts.size()][s]++; } void dump(const size_t channel) const { for(auto [value, counter] : counts[channel]) std::cout << value << '\t' << counter << '\n'; } void mid_channel(const std::vector<short>& samples) { for(auto i = 0; i < samples.size()/2; i++) counts[0][(samples[2*i] + samples[2*i+1]) / 2]++; } The final output is shown in the dump function (freq count_value). How can I transform this to draw an histogram? output desired Something like gnuplotdoes.
The C++ standard itself does not provide any classes for visualization or graphical user interfaces. There are, of course, many frameworks and libraries available for that. Since you already know gnuplot, you may be interested in a C++ interface for gnuplot. Other alternatives include Qt Charts or Boost.Python. See also this question.
73,894,588
74,657,856
getting nested values from a decoded SAMLresponse XML with rapidxml
I have been trying to get the values of the decoded XML, all 3 of them. The XML file is as follows (it has way more nodes but this is just a testing preview) <Response ID="number" Version="2.0"> <Issuer xmlns=":assertion"> check1 </Issuer> <Status> <StatusCode Value="Success" /> checkcheck2 </Status> <Assertion ID="somenumber" IssueInstant="datestamp" Version="2.0" xmlns="urn:oasis:names:tc:SAML:2.0:assertion"> <Issuer> checkcheckcheck3 </Issuer> </Assertion> </Response> I tried to get the value out off the "Status" node in the following way (don't mind the includes I don't need I have been trying a lot of things and just keep them for now incase I need them, will remove them when it is working): #include <iostream> #include <sstream> #include <iostream> #include <cstring> #include <string> #include <fstream> #include <vector> #include "rapidxml.hpp" #include "rapidxml_print.hpp" #include "base64.hpp" using namespace std; int main() { rapidxml::xml_node<> *root_node; rapidxml::xml_node<> *second_node; //costum base64 encoder and decoder this works as it should help::base64_decode; string xmlFile; // Base64 response from form data contains xml xmlFile = help::base64_decode("the base64 encoded SAMLResponse"); //put the b64 decoded xml in a string stringstream decodedXml(xmlFile); rapidxml::xml_document<> doc; // test the decoded b64 cout << xmlFile << endl; // Read file into vector<char> vector<char> buffer((istreambuf_iterator<char>(decodedXml)), istreambuf_iterator<char>()); buffer.push_back('\0'); doc.parse<0>(&buffer[0]); root_node = doc.first_node("Response"); // this returs Issuer cout << root_node->first_node()->name() << endl; // go to next sibling of the root node ?? (that should be Status) second_node = root_node->next_sibling(); // gives me a exited with code=3221225477 in 0.485 seconds on compiling cout << second_node->first_node()->name() << endl; What am I doing wrong, or rather. What part of the next_sibling() function am I misunderstanding. As far as I know the next_sibling() would go to the next node that is on the same level as the one declared as root_node (which is Issuer in this case).
In case anyone is wondering what i did to fix not being able to search nodes by string input. i wrote a function that searches for sibling nodes. //gets the coun of child nodes present in current node int getChildCount(rapidxml::xml_node<> *n) { int c = 0; for (rapidxml::xml_node<> *child = n; child != NULL; child = child->next_sibling()) { c++; } return c; } static rapidxml::xml_node<> *find_sibling(rapidxml::xml_node<> *in, const std::string &s) { rapidxml::xml_document<> doc_error; rapidxml::xml_node<> *err = doc_error.allocate_node(rapidxml::node_element, "error"); doc_error.append_node(err); std::string node_name; int childs = getChildCount(in); int count = 1; while (in != NULL) { in = in->next_sibling(); count++; node_name = in->name(); if (node_name == s) { return in; } if (count == childs) { return err; } } return err; } This now allows me to search with; rapidxml::xml_node<> *issuer_node = find_sibling(issuer_node->first_node(), "Assertion"); This wil go through the function to try and find Assertion node. And if it can not be found it within the sibling nodes instead of just crashing, it returns a xml doc with .
73,894,743
73,901,210
ROS2 publish mesh marker
I'm trying to display a mesh resource in Rviz. It must be pretty straightforward as was in ROS1, but I'm not sure why it is not working. Here is a sample code I tried: // meshpub.cpp #include <rclcpp/rclcpp.hpp> #include <std_msgs/msg/color_rgba.hpp> #include <geometry_msgs/msg/pose.hpp> #include <visualization_msgs/msg/marker.hpp> #include <ament_index_cpp/get_package_share_directory.hpp> using namespace std; int main(int argc, char ** argv) { (void) argc; (void) argv; rclcpp::init(argc, argv); rclcpp::Node node("shape_pubilsher"); string base_frame = "base_link"; string topic = "/marker"; // Getting the model file path: auto package_share_directory = ament_index_cpp::get_package_share_directory("package"); auto file_name = package_share_directory.append("/meshes/model.obj"); auto qos = rclcpp::QoS(1000); auto publisher = node.create_publisher<visualization_msgs::msg::Marker>(topic, qos); RCLCPP_INFO(node.get_logger(), "Waiting for Rviz to load..."); while(node.get_node_graph_interface()->count_subscribers(topic) == 0) { rclcpp::sleep_for(200ms); } // Creating the marker and initialising its fields geometry_msgs::msg::Pose pose; pose.position.x = 0; pose.position.y = 0; pose.position.z = 0; pose.orientation.x = 0; pose.orientation.y = 0; pose.orientation.z = 0; pose.orientation.w = 0; std_msgs::msg::ColorRGBA colour; colour.a = 1; colour.r = 1; colour.g = 0; colour.b = 0; visualization_msgs::msg::Marker marker; marker.header.frame_id = base_frame; marker.header.stamp = node.now(); marker.action = visualization_msgs::msg::Marker::ADD; marker.type = visualization_msgs::msg::Marker::MESH_RESOURCE; marker.pose = pose; marker.id = 0; marker.mesh_resource = file_name; marker.scale.x = 2; marker.scale.y = 2; marker.scale.z = 2; marker.color = colour; RCLCPP_INFO(node.get_logger(), "Attempting to publish mesh"); publisher->publish(marker); while(rclcpp::ok()); return 0; } I have installed the meshes folder which contains 3D model files onto the package share directory. I have tried different model file formats like .obj, .fbx, .blend and .dae (all were supported in ROS1 Rviz), but Rviz refuses to display it, and all I get is this heartwarming congratulation message: [INFO] [launch]: Default logging verbosity is set to INFO [INFO] [rviz2-1]: process started with pid [4733] [INFO] [meshpub-2]: process started with pid [4735] [meshpub-2] [INFO] [1664444431.191595500] [meshpub]: Waiting for Rviz to load... [rviz2-1] QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-amirint' [rviz2-1] [INFO] [1664444431.789824400] [rviz2]: Stereo is NOT SUPPORTED [rviz2-1] [INFO] [1664444431.790017200] [rviz2]: OpenGl version: 3.1 (GLSL 1.4) [rviz2-1] [INFO] [1664444431.863061600] [rviz2]: Stereo is NOT SUPPORTED [meshpub-2] [INFO] [1664444433.394043100] [meshpub]: Attempting to publish mesh [rviz2-1] [ERROR] [1664444434.023035400] [rviz2]: Could not load resource [/mnt/e/avnv/ros2_visually/install/package/share/package/meshes/model.obj]: Unable to open file "/mnt/e/avnv/ros2_visually/install/package/share/package/meshes/model.obj". Although /mnt/e/avnv/ros2_visually/install/package/share/package/meshes/model.obj is the correct path of the resource, the error message does not specifically tell whether this is a no such file or directory or a file format not supported sort of thing. It only says Unable to open file .... I'm using Ubuntu 20.04 on wsl2 with ROS_DISTRO=galactic.
File paths have to be in the form file:///path/to/file or package://path/to/file. I mistakenly assumed ament_index_cpp::get_package_share_directory("package") will by default return the path in the mentioned form. So just manually appending a file:// to the returned path string fixed the issue.
73,894,913
73,894,984
The compiler bug? Returning std::vector and std::string in std::tuple. But I got strange values
I would like to return multiple values and declare that function using auto. But that does not work well. Values can not be returned correctly. It was overwritten. I try to execute following functions f1~f3. Those function should return vector and string in tuple. But only f3 works well. #include <iostream> #include <vector> #include <string> #include <tuple> auto f1(){ std::vector<double> v(10, 0); std::string s = "hello"; return std::forward_as_tuple(v, s); } auto f2(){ std::vector<double> v(10, 0); return std::forward_as_tuple(v, "hello"); } std::tuple<std::vector<double>, std::string> f3(){ std::vector<double> v(10, 0); std::string s = "hello"; return std::forward_as_tuple(v, s); } int main(void){ //change the function //auto [vec, str] = f1(); //auto [vec, str] = f2(); auto [vec, str] = f2(); for (auto e : vec){ std::cout << "vec : " << e << std::endl; } std::cout << "str : " << str << std::endl; } You can also execute this program at online compiler wandbox from this link. f1() causes an segmentation fault. f2() returns wrong values in std::vector. It seems random number. f3() returns all values correctly. Why does this problem occur? Is it impossible to return multiple values and declare that function using auto?
The problem occurs because std::forward_as_tuple returns references to local variables - the return type is tuple<vector<double>&,string&>. The first two functions produce undefined behaviour. The third one works because you explicitly return by value, although the forwarding doesn't work because you did not move the l-values so they get copied into the returned tuple. The correct way to return a tuple is just: return std::tuple{std::move(vec),std::move(str)};
73,895,431
74,003,596
Unresolved External Symbol while trying to use bit7z library C++ / Qt
I've been trying to install and properly link bit7z into my C++ code as I have to do a task for my internship which concludes in automatically zipping a certain directory and sending the zip-file out as an email. Right now the email is not interesting to me as I can't even get the base program. I just keep getting the Linker Error 2019 and I don't know what to do anymore. I'll provide as much info as I can. I use Visual Studio 2019. My .pro file: TEMPLATE = app TARGET = aixLogger DESTDIR = ./Debug CONFIG += debug console DEPENDPATH += . MOC_DIR += . OBJECTS_DIR += debug UI_DIR += GeneratedFiles RCC_DIR += GeneratedFiles LIBS += -D:/local/aretz/Programmierung/git-workplace/aixLogger/Dependencies/bit7z/lib -lbit7z INCLUDEPATH += D:/local/aretz/Programmierung/git-workplace/aixLogger/Dependencies/bit7z/include include(aixLogger.pri) My .h #pragma once #include <qwidget.h> #include <qobject.h> #include <bit7z.hpp> class AIXLogger : public QWidget { Q_OBJECT public slots: public: void CompressDir(); void Execute(); }; My .cpp #include <QCoreApplication> #include <string> #include <iostream> #include <filesystem> #include <bit7z.hpp> #include "main.h" #include "bitcompressor.hpp" namespace fs = std::filesystem; using namespace bit7z; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); std::string path = "C:/Users/aretz/Downloads/test"; for (const auto& entry : fs::directory_iterator(path)) std::cout << entry.path() << std::endl; //return a.exec(); } void AIXLogger::CompressDir() { try { Bit7zLibrary lib{ L"C:/Program Files/7-Zip/7z.dll" }; //BitCompressor compressor{ lib, BitFormat::Zip }; std::vector< std::wstring > files = { L"aretz/downloads/test/test1.txt", L"aretz/downloads/test/test1.txt" }; //Zip Archiv erstellen //compressor.compress(files, L"output_archive.zip"); //Directory zippen //compressor.compressDirectory(L"dir/path/", L"dir_archive.zip"); } catch (const BitException& ex) { //irgendwas mit &ex machen } } void AIXLogger::Execute() { CompressDir(); } I'm also adding pictures of the properties I changed. Additional DependenciesAdditional Library DirectoriesAdditional Include Directories EDIT: Here is the actual Error I'm getting with just the line "Bit7zLibrary lib {L"C:/Program Files/7-Zip/7z.dll" };: Error LNK2019 unresolved external symbol "public: __thiscall bit7z::Bit7zLibrary::Bit7zLibrary(class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> > const &)" (??0Bit7zLibrary@bit7z@@QAE@ABV?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@std@@@Z) referenced in function "public: void __thiscall AIXLogger::CompressDir(void)" (?CompressDir@AIXLogger@@QAEXXZ) aixLogger D:\local\aretz\Programmierung\git-workplace\aixLogger\main.obj 1 Severity Code Description Project File Line Suppression State Error LNK2019 unresolved external symbol "public: virtual __thiscall bit7z::Bit7zLibrary::~Bit7zLibrary(void)" (??1Bit7zLibrary@bit7z@@UAE@XZ) referenced in function "public: void __thiscall AIXLogger::CompressDir(void)" (?CompressDir@AIXLogger@@QAEXXZ) aixLogger D:\local\aretz\Programmierung\git-workplace\aixLogger\main.obj 1
The problem you're having is that the linker cannot find the bit7z static library. By default, the bit7z library is built to bit7z\bin\$(PlatformShortName)\, where $(PlatformShortName) is either x86 or x64 according to your target architecture. However, you specified a different library directory (bit7z\lib\), which is wrong (unless you changed the directory where you output the built library). You can fix it by changing the path to $(SolutionDir)Dependencies\bit7z\bin\$(PlatformShortName)\. Also, please note that, on x86, the default library name is just bit7z.lib, while on x64 is bit7z64.lib.
73,895,736
73,895,788
C/C++ Little/Big Endian handler
There are two systems that communicate via TCP. One uses little endian and the second one big endian. The ICD between systems contains a lot of structs (fields). Making bytes swap for each field looks like not the best solution. Is there any generic solution/practice for handling communication between systems with different endianness?
Generally speaking, values transmitted over a network should be in network byte order, i.e. big endian. So values should be converted from host byte order to network byte order for transmission and converted back when received. The functions htons and ntohs do this for 16 bit integer values and htonl and ntohl do this for 32 bit integer values. On little endian systems these functions essentially reverse the bytes, while on big endian systems they're a no-op. So for example if you have the following struct: struct mystruct { char f1[10]; uint32_t f2; uint16_t f3; }; Then you would serialize the data like this: // s points to the struct to serialize // p should be large enough to hold the serialized struct void serialize(struct mystruct *s, unsigned char *p) { memcpy(p, s->f1, sizeof(s->f1)); p += sizeof(s->f1); uint32_t f2_tmp = htonl(s->f2); memcpy(p, &f2_tmp, sizeof(f2_tmp)); p += sizeof(s->f2); uint16_t f3_tmp = htons(s->f3); memcpy(p, &f3_tmp, sizeof(f3_tmp)); } And deserialize it like this: // s points to a struct which will store the deserialized data // p points to the buffer received from the network void deserialize(struct mystruct *s, unsigned char *p) { memcpy(s->f1, p, sizeof(s->f1)); p += sizeof(s->f1); uint32_t f2_tmp; memcpy(&f2_tmp, p, sizeof(f2_tmp)); s->f2 = ntohl(f2_tmp); p += sizeof(s->f2); uint16_t f3_tmp; memcpy(&f3_tmp, p, sizeof(f3_tmp)); s->f3 = ntohs(f3_tmp); } While you could use compiler specific flags to pack the struct so that it has a known size, allowing you to memcpy the whole struct and just convert the integer fields, doing so means that certain fields may not be aligned properly which can be a problem on some architectures. The above will work regardless of the overall size of the struct.
73,895,847
73,896,033
language c++, Error invalid types 'int[int]' for array subscript
I find the error that is in the title, this in my program that is a static queue with all its methods or functions, this error is in the following function. void Cola::queve(TIPO_DATO datos){ if(cola1.vacia()){ final = (final+1)%TAM; datos[final] = datos; }else{ cout<<"No hay espacios en la cola"<<endl; } } Anyway I leave the rest of the code in case something, I hope your answers thanks. #include <iostream> #include <stdlib.h> using namespace std; #define TAM 10 #define TIPO_DATO int void menu(); class Cola{ private: TIPO_DATO datos[TAM]; int frente; int final; public: void inicializa(); bool vacia(); bool llena(); TIPO_DATO front(); void queve(TIPO_DATO datos); void deque(); void imprimir(); void anular(); }; int main(){ menu(); return 0; } Cola cola1; void menu(){ int opc; int a; cola1.inicializa(); cout<<"\t \t ***** MENU PRINCIPAL *****"<<endl; cout<<"Selecciona la opcion deseeada"<<endl; cout<<"1. Vacia"<<endl; cout<<"2. Llena"<<endl; cout<<"3. Front"<<endl; cout<<"4. Encolar"<<endl; cout<<"5. Deseencolar"<<endl; cout<<"6. Imprimir"<<endl; cout<<"7. Anular"<<endl; cout<<"8. Salir"<<endl; cin>>opc; cout<<endl; switch(opc){ case 1: cola1.vacia(); break; case 2: break; case 3: cout<<"cola1.front()"<<endl; break; case 4: break; case 5: break; case 6: break; case 7: cola1.anular(); break; case 8: break; } } //Prototipos de la cola void Cola::inicializa(){ frente = 0; final = TAM-1; } bool Cola::vacia(){ if(frente == 0 && final == TAM-1){ return true; cout<<endl; cout<<"La cola se encuentra vacia"<<endl; }else{ return false; cout<<endl; cout<<"La cola no esta vacia"<<endl; } system("PAUSE"); menu(); } bool Cola::llena(){ } void Cola::queve(TIPO_DATO datos){ if(cola1.vacia()){ final = (final+1)%TAM; datos[final] = datos; }else{ cout<<"No hay espacios en la cola"<<endl; } } void Cola::deque(){ } TIPO_DATO Cola::front(){ if(cola1.vacia()){ return datos[frente]; } else{ cout<<"Error"<<endl; } } void Cola::imprimir(){ } void Cola::anular(){ frente = 0; final = TAM-1; }
The function parameter datos hides the members variable of the same name, either use different name: void Cola::queve(int new_datos){ if(cola1.vacia()){ final = (final+1)%TAM; datos[final] = new_datos; }else{ cout<<"No hay espacios en la cola"<<endl; } } or use this-> for the hidden member variable: void Cola::queve(int datos){ if(cola1.vacia()){ final = (final+1)%TAM; this->datos[final] = datos; }else{ cout<<"No hay espacios en la cola"<<endl; } }
73,896,217
73,896,375
Minimum in bitonic array with plateaus
I'm trying to find minimum in array which has this kind of structure in general: Array consists of non-negative integers [0; 1e5-1]. It may contain any number of such steps, be sorted or just a constant. I want to find it in O(logn) thats why I'm using binary search. This code handle all cases except cases there is any plateau: size_t left = 0, right = arr.size() - 1; while (left < right) { const size_t mid = left + (right - left) / 2; if ((mid == 0 || arr[mid] < arr[mid - 1]) && (mid + 1 == size || arr[mid] < arr[mid + 1])) { return mid; } if (arr[mid] > arr[mid + 1] || arr[mid] > arr[right]) { left = mid + 1; } else { right = mid; } } return left; Example of bad input: [4, 3, 3, 2, 1, 2]. Unfortenatly, I'm out of ideas how to fix this cases. Maybe it's even impossible. Thank you in advance.
I am afraid it is not possible to do in log n time in general. Assume an array of n elements equal to 1 and a single element of 0. Your problem now reduces into finding that 0 element. By "visiting" (=indexing) any member 1 you gain no knowledge about position of 0 - making the search order irrelevant. Therefore you have to visit every element to find where the 0 is. If you really want, I think the following algorithm should be roughly O(log n + #elements-on-plateaus) Set left, right as for binary search Compute middle. Go left from middle until: If you find a decrease, set right=pos where pos is the decreased element and go 4. If you find an increase, set left=pos where pos is the increased element and go 4. If you reach left position, go right from middle instead and do the analogous actions. [X] If you reach right too, you are on a plateau and range [left,right] are the minimal elements of the array. Repeat until you hit [X].
73,896,764
73,896,830
C++20 Concepts Apply constraint on templated function
I'd like to start with c++20 concepts. class MyClass { template<typename T> void copy(const T& data); }; copy() only works if T is is_trivially_copyable. Before C++20 I'd have used static_assert(is_trivially_copyable<T>, "Type must be trivially copyable"); within the copy function. But from my understanding, this is an issue where concepts can be used. After some googling I came up with template <typename T> concept isTriviallyCopyable = std::is_trivially_copyable_v<T>; however when adding this to the function class MyClass { template<isTriviallyCopyable> void copy(const isTriviallyCopyable & data); }; This gives me a compiler error. Could you help me out here?
You need to add a type parameter for your sTriviallyCopyable to be applied to. That would give you class MyClass { template<isTriviallyCopyable T> void copy(const T & data); };
73,897,460
73,899,122
Random results when passing byte array from c++ DLL to c# client
I am passing a byte array from a function inside c++ DLL to a c# client. I am using a widely suggested method IntPtr pointer in C# and then Marshal.Copy to create byte array in the C# client. When I read the resulting array it seem I am getting random values. No actual values from the DLL are passed. It seems the IntPnt is pointing at some random memory address? Here is the code: C++ DLL extern "C" __declspec(dllexport) char* __stdcall passBytes() { cout << "\n passBytes DLL code START \n"; char bytes[] = { 0x07, 0x08 }; cout << "bytes array size: " << sizeof(bytes) << endl; for (int i = 0; i < sizeof(bytes); i++) { cout << "byte " << i << " = " << (int)bytes[i] << endl; } char* bptr = bytes; cout << "\n passBytes DLL code END \n"; return bptr; } C# client namespace sc_client { class Program { static void Main(string[] args) { const string libname = "C:/work/x64/Release/libMxN.dll"; [DllImport(libname)] static extern IntPtr passBytes(); IntPtr ptr = passBytes(); byte[] cbytes = new byte[2]; Marshal.Copy(ptr, cbytes, 0, 2); Console.WriteLine("C# client output: "); for ( int i = 0; i < cbytes.Length; i++) { Console.WriteLine("client byte " + i + " = " + (int)cbytes[i]); } } } } Outputs ( just relaunched the app 4 times without any modifications in the code) 1. passBytes DLL code START bytes array size: 2 byte 0 = 7 byte 1 = 8 passBytes DLL code END C# client output: client byte 0 = 176 client byte 1 = 232 2. passBytes DLL code START bytes array size: 2 byte 0 = 7 byte 1 = 8 passBytes DLL code END C# client output: client byte 0 = 144 client byte 1 = 232 3. passBytes DLL code START bytes array size: 2 byte 0 = 7 byte 1 = 8 passBytes DLL code END C# client output: client byte 0 = 176 client byte 1 = 228
Your primary issue appears to be that the char* array is declared locally, and disappears as soon as the function finishes. One way to do this properly is to allocate it on the heap, and make a separate Free function. But you are far better off just passing in a buffer. I'm not familiar with C++ very much, but something like this would be your function extern "C" __declspec(dllexport) void __stdcall passBytes(char* bytes, int size) { .... And then in C# you use it like this const string libname = "C:/work/x64/Release/libMxN.dll"; [DllImport(libname)] static extern void passBytes([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)][Out] byte[] bytes, int size); static void Main(string[] args) { byte[] cbytes = new byte[2]; passBytes(cbytes, cbytes.Length); Console.WriteLine("C# client output: "); for ( int i = 0; i < cbytes.Length; i++) { Console.WriteLine("client byte " + i + " = " + (int)cbytes[i]); } }
73,897,702
73,897,781
Get return code of a child process created with fork()
I'm trying to get the return code of the child process created by fork(). I'm using wait() function to get the return code. Everything is working fine but the return values given by wait() is 256 times the actual return value. Can anybody explain why is that. Code: #include <iostream> #include <unistd.h> #include <sys/wait.h> constexpr int PROCESS_COUNT = 7; int main() { pid_t pid; for (int i = 0; i < PROCESS_COUNT; i++) { pid = fork(); if (pid > 0) { int returnCode; int pid; pid = wait(&returnCode); std::cout << "\n Process: " << pid << "; i: " << i << "; Return Code: " << returnCode << std::endl; } else { return i; } } return EXIT_SUCCESS; } Output: Process: 7910; i: 0; Return Code: 0 Process: 7911; i: 1; Return Code: 256 Process: 7912; i: 2; Return Code: 512 Process: 7913; i: 3; Return Code: 768 Process: 7914; i: 4; Return Code: 1024 Process: 7915; i: 5; Return Code: 1280 Process: 7916; i: 6; Return Code: 1536
Please read the wait manual page. The value given by wait doesn't only contain the child-process exit code, but also other flags and values. To get the exit status you first need to make sure that the child-process really exited the normal way. This is done with the WIFEXITED macro. Then to get the actual status use the WEXITSTATUS macro. Something like this: pid_t pid = wait(&returnCode); if (pid >= 0 && WIFEXITED(returnCode)) { std::cout << "Child process " << pid << " exited normally with return code " << WEXITSTATUS(returnCode) << '\n'; } Note that I added the "correct" type actually returned by wait, and that I also check it to make sure that wait didn't fail.
73,897,975
73,898,082
How do I parse a string delimited by / into an array?
I have tried several methods of parsing a string and adding the elements to an array with using a / as a delimiter. I know I will eventually need to use stod(). Can anyone point me in the right direction? I will need to parse the string rec. void make_record() { int size = 4; double* record = nullptr; string rec; cout << "Enter record of items separated by a space " << endl; cout << "Item ID/Quantity/WholesaleCost/RetailCost" << endl; cin >> rec; // string to parse //Current: 12345 27.5 82.4 5.3 //Goal: 12345/27.5/82.4/5.3 //current approach record = new double[size]; for (int i = 0; i < size; i++) { cin >> record[i]; } //What I have tried - probably very wrong string delimiter = "/"; size_t pos = 0; std::string token; while ((pos = rec.find(delimiter)) != std::string::npos) { token = rec.substr(0, pos); rec.erase(0, pos + delimiter.length()); record[pos] = stod(token); cout << record[pos]; } }
It's really not a lot more complicated than your current approach. // better approach record = new double[size]; for (int i = 0; i < size - 1; i++) { char slash; cin >> record[i] >> slash; } cin >> record[size - 1]; The slash variable reads (and discards) the slashes in your input. Because the last number is not followed by a slash, it must be read separately, after the main loop. Now this approach doesn't do any error checking at all, but given correct input it works.
73,898,385
73,916,623
Load and Set Skeletal Mesh and Animation at runtime
I have a generic vehicle class, derived from the standard AWheeledVehiclePawn and I would like to load and change skeletal mesh and wheels animation at runtime depending on a vehicle type enum in input. If I spawnm cars and set these assets from the editor, everything works fine, but if I try to set them programmatically from code, only the mesh is set, the animation is not working (wheels just not spinning / steering). So the question is: how to set these two assets at runtime (or other approach, how to have a generic animation that works for all the different vehicle models and minimize the setup from code)? Thanks! Here some code: UCLASS() class MY_API ACar : public AWheeledVehiclePawn { GENERATED_UCLASS_BODY() public: void SetEntityType(const EntityType& type); private: void SetMeshAndAnim(); ... } ACar::ACar(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { meshReferenceFolders_.Add(EntityType::Car1, L"Car1"); ... meshReferenceFolders_.Add(EntityType::CarN, L"CarN"); for (auto& meshPath : meshReferenceFolders_) { ConstructorHelpers::FObjectFinder<USkeletalMesh> mesh( std::wstring(L"SkeletalMesh'" + ModelFolder + meshPath.Value + L"/" + meshPath.Value + L"." + meshPath.Value + L"'").data() ); ConstructorHelpers::FObjectFinder<USkeleton> skeleton( std::wstring(L"Skeleton'" + ModelFolder + meshPath.Value + L"/" + meshPath.Value + L"_Skeleton." + meshPath.Value + L"_Skeleton'").data() ); if (skeleton.Object) mesh.Object->SetSkeleton(skeleton.Object); ConstructorHelpers::FObjectFinder<UAnimBlueprint> animation( std::wstring(L"UAnimBlueprint'" + ModelFolder + meshPath.Value + L"/" + meshPath.Value + L"_AnimBlueprint." + meshPath.Value + L"_AnimBlueprint'").data() ); meshes_.Add(meshPath.Key, mesh.Object); anims_.Add(meshPath.Key, animation.Object); } } void ACar::SetEntityType(const EntityType& type) { carType_ = type; SetMeshAndAnim(); } void ACar::SetMeshAndAnim() { GetMesh()->SetSkeletalMesh(meshes_[carType_]); GetMesh()->SetAnimInstanceClass(anims_[carType_]->GeneratedClass); } caller void UManager::UManager() { ... static ConstructorHelpers::FObjectFinder<UBlueprint> asset( TEXT("Blueprint'/Game/Blueprints/BPCar.BPCar'") ); if (asset.Object) { importedCarInstance= asset.Object->GeneratedClass; } ... } void UManager::TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction ) { ... if (spawn) { auto car = World->SpawnActor<ACar>(importedCarInstance, location, rotation, spawnParameters); car->SetEntityType(obj.type); } }
For some unknown reasons I found that there was no controller associated to the spawned actor, and then the ChaosVehicleComponent was not able to set the throttle and steering values provided. To solve this, I just added an AIController, move all the automatic movement logic there, and associated it to my car when created
73,898,475
73,898,513
C++ Reimplementing assignable "at()" function of vector
What i discovered I discover that C++ vector::at() is an assignable function, how is it possible? I mean I can call at() function to get the value of vector at certain position, and i can assign a value to a certain position of the vector. std::vector<int> vec; vec.push_back(4); vec.push_back(5); vec.push_back(6); //get val at position cout << vec.at(0)<<endl; //it print 4 //set val at position vec.at(0) = 89; std::cout << vec.at(0)<<endl; //it print 89 What I want to do I want to reimplement in my own vector class without inherit it or copy the original class; how can i do it? class myIntVector { int arraye[50] = {0}; //other class function and constructor public: int at(int index) { //some code } };
I want to reimplement in my own vector class without inherit it or copy the original class; how can i do it? Not trying to sound too snarky but you could read the documentation: Return value Reference to the requested element. Therefore something like this: class myIntVector { int arraye[50] = {0}; //other class function and constructor public: int& at(int index) { return arraye[index]; } }; Also your indices should be std::size_t, and std::array is preferred to C-style arrays.
73,899,093
73,899,818
Interfacing C++ iterators from C
I'm writing a C backend for a C++ library and I want the C code to be able to iterate over the individual items of a forward iterator. In C++ the code which iterates over the items looks like this: auto rng = wks.range(XLCellReference("A1"), XLCellReference("Q1")); for (auto& cell : rng) { // do something with "cell" } Now I want to export this code so that it is accessible from C. I'd like to be able to iterate over the items from C using a set of functions like this: void *startiteration(void *cpp_obj); void *getnextitem(void *cpp_obj, void *iter); void finishiteration(void *cpp_obj, void *iter); I'd imagine startiteration() to return an iterator pointer to the C code which would then be passed along with the C++ object pointer for all successive calls to getnextitem() and finishiteration(). But the problem here is that I can easily pass pointers of objects created in C++ using new between C and C++ code but I don't see how I could do the same with iterators since the iterators are returned by a class method and I don't think there's any way to turn the iterator into a pointer that I could pass to C code which would then pass it back to C++ during the iteration. Also, I don't know how I would "free" such an iterator. Does anybody have some tips how I can iterate over a C++ forward iterator from C code? How should this be implemented? EDIT Implementation based on Silvio's suggestions: struct myiter { XLCellIterator begin; XLCellIterator end; }; void *xlsx_startiteration(void *handle, int idx) { XLDocument *doc = (XLDocument *) handle; XLWorkbook wb = doc->workbook(); auto wks = wb.worksheet(wb.sheetNames()[idx-1]); XLCellRange cr = wks.range(XLCellReference("A1"), XLCellReference("Q1")); myiter *it = new myiter(); it->begin = std::begin(static_cast<XLCellRange*>(cr)); it->end = std::end(static_cast<XLCellRange*>(cr)); return it; }
auto rng = wks.range(XLCellReference("A1"), XLCellReference("Q1")); for (auto& cell : rng) { // do something with "cell" } I like doing 1:1 relationship between C++ and C. The following code outputs 3 lines var=1 var=2 var=3. By wrapping the objects inside structures, the C side only forward declarations of structures and pointers. The C++ side sees all the rest. Additionally, C side will get a warning when passing invalid pointer to the wrong function. #include <cstdio> #include <vector> typedef int do_not_know_what_is_the_type; typedef std::vector<do_not_know_what_is_the_type> XLCellRange; typedef XLCellRange::iterator XLCellIterator; // header file // C side #ifdef __cplusplus extern "C" { #endif struct wks_range_it_s; void wks_range_it_inc(struct wks_range_it_s *); bool wks_range_it_ne(struct wks_range_it_s *, struct wks_range_it_s *); do_not_know_what_is_the_type wks_range_it_deref(struct wks_range_it_s *); void wks_range_it_destruct(struct wks_range_it_s *); struct wks_range_s; struct wks_range_s *wks_range_construct(); void wks_range_destruct(struct wks_range_s *); struct wks_range_it_s *wks_range_begin(struct wks_range_s *); struct wks_range_it_s *wks_range_end(struct wks_range_s *); #ifdef __cplusplus } #endif #ifdef __cplusplus // C++ side struct wks_range_s { XLCellRange rng; }; struct wks_range_it_s { XLCellIterator it; }; extern "C" void wks_range_it_inc(struct wks_range_it_s *t) { ++t->it; } extern "C" bool wks_range_it_ne(struct wks_range_it_s *a, struct wks_range_it_s *b) { return a->it != b->it; } extern "C" do_not_know_what_is_the_type wks_range_it_deref(struct wks_range_it_s *t) { return *t->it; } extern "C" void wks_range_it_destruct(struct wks_range_it_s *t) { delete t; } extern "C" struct wks_range_s *wks_range_construct() { // return new struct wks_range_s(wks.range(XLCellReference("A1"), XLCellReference("Q1"))); return new wks_range_s{{1,2,3}}; } extern "C" void wks_range_destruct(struct wks_range_s *t) { delete t; } extern "C" struct wks_range_it_s *wks_range_begin(struct wks_range_s *t) { return new wks_range_it_s{t->rng.begin()}; } extern "C" struct wks_range_it_s *wks_range_end(struct wks_range_s *t) { return new wks_range_it_s{t->rng.end()}; } #endif int main() { // C code example struct wks_range_s *rng = wks_range_construct(); // Almost 1:1 relationship with C++ range loop. for(struct wks_range_it_s *begin = wks_range_begin(rng), *end = wks_range_end(rng); wks_range_it_ne(begin, end) ? 1 : ( // Yes, I'm sneaky. wks_range_it_destruct(begin), wks_range_it_destruct(end), 0); wks_range_it_inc(begin) ) { do_not_know_what_is_the_type var = wks_range_it_deref(begin); // do something with var here? printf("var=%d\n", var); } wks_range_destruct(rng); }
73,899,269
73,899,573
Conditionally initialize class variable depending on the template type
Suppose I have the following code: enum class Type { Type32, Type64 }; template<Type T> class MyClass { public: using MyType = typename std::conditional<T == Type::Type32, uint32_t, uint64_t>::type; MyType getSum() { MyType sum = 0; for(size_t i = 0;i < sizeof(arr);i ++) { sum += arr[i]; } return sum; } private: //MyType arr[4] = { 0x1234, 0x5678, 0x9ABC, 0xDEF0 }; // for Type::Type32 //MyType arr[2] = { 0x12345678, 0x9ABCDE }; // for Type::Type64 }; I try to initialize a class variable depends on the template type with the same name but different type and value. How can I do that? I probably looking for a solution that works in c++11.
Here is a simple way: #include <array> #include <cstdint> #include <type_traits> enum class Type { Type32, Type64 }; template <Type> struct As128Bits; template <> struct As128Bits<Type::Type32> { using Integer = std::uint32_t; std::array<Integer, 4> data{0x1234, 0x5678, 0x9ABC, 0xDEF0}; }; template <> struct As128Bits<Type::Type64> { using Integer = std::uint64_t; std::array<Integer, 2> data{0x12345678, 0x9ABCDE}; }; template <Type T> struct MyClass : private As128Bits<T> { using Integer = typename As128Bits<T>::Integer; using As128Bits<T>::data; Integer getSum() { Integer sum = 0; for (auto const val : data) { sum += val; } return sum; } };
73,899,540
73,900,513
How can I resume a stopped process?
Following this documentation, I am testing how to stop and resume a process. I have basic code to test as follows: #include <iostream> #include <csignal> #include <unistd.h> int main() { std::cout << "Hello" << std::endl; int pid = getpid(); kill(pid, SIGSTOP); kill(pid, SIGCONT); std::cout << "Bye" << std::endl; return 0; } The output is: Hello It stops the process, but it never resumes it. How should I fix it?
A solution, if a bit complicated, is to create a child process to start and stop the parent. Here is a small code example, that might help: #include <iostream> #include <csignal> #include <unistd.h> int pid; //Include declaration outside so it transfers to the child process int main() { std::cout << "Hello" << std::endl; pid = getpid(); int returned_pid = fork(); //Duplicate process into 2 identical processes if(returned_pid) { // If it is the parent process, then fork returns the child process pid // This is executed by the parent process usleep(1000); // Sleep a millisecond to allow for the stop command to run } else { // If fork returns 0, then it is the child process // The else is executed by the child process kill(pid, SIGSTOP); // Stop parent process usleep(3000000); // Delay 3 seconds kill(pid, SIGCONT); // Resume parent process } if(returned_pid) { // Only print if parent process std::cout << "Bye" << std::endl; } return 0; } Clarification: The fork command returns 2 different values in the 2 processes: 0 in the child, and the pid of the child process in the parent. Other note: When running this in a terminal, it will look weird, as the terminal may note that the process was stopped and give a new command line, but then the process resumes, so prints Bye over it. Just a note.
73,899,992
73,900,072
How can I kill a function after a timeout in Qt?
I have a function, let's call it foo(). void foo() { int count = 0; while(1) { count ++; if(count>= 30000) { count = 0; } } } foo() will run indefinitely, but let's say I want to fun my function foo() after 1 minute. How can I do that using Qt? I have already seen some people talking about one shot Qtime, but all the examples I have seen are about running my function after the timeout, but never killing it.
You shouldn't kill threads but instead give them a condition to check if they should continue or quit. One way could use an atomic<bool> so that you can set it from another thread. You could also limit the time by measuring how long time the function has executed. Example: #include <atomic> #include <chrono> void foo(std::atomic<bool>& run) { auto end_at = std::chrono::steady_clock::now() + std::chrono::minutes(1); while(run == true && std::chrono::steady_clock::now() < end_at) { count++; } } Setting run to false from another thread would signal foo() to quit and if it runs for longer than a minute it'll also quit.
73,900,540
73,901,478
Why is a C++ lambda life cycle bound to the smallest block scope?
In the following example program, I would expect the counter to reset at the beginning of each cycle: #include <iostream> #include <functional> void run_lambda(std::function<void()> fun){ fun(); fun(); } int main(){ for(int i = 0; i < 3 ; ++i){ run_lambda([i](){ static int testVal = 0; std::cout << "value[" << i << "]:" << testVal << std::endl; ++testVal; }); } return 0; } Instead the output is: value[0]:0 value[0]:1 value[1]:2 value[1]:3 value[2]:4 value[2]:5 According to this answer: The closure type is declared in the smallest block scope, class scope, or namespace scope that contains the corresponding lambda-expression. In my understanding this means, that the lambda object life cycle is bound to the loops block scope, thus the static variable is not resetting at the start of the loop. Is there a specific reason for this? Intuitively one would think that a lambda expression is essentially a temporary object, and as such in this example it would cease to exist after the statement.
Your code is basically equivalent to: #include <iostream> #include <functional> struct lambda { lambda(int i): i(i) {} int i; void operator()() { static int testVal = 0; std::cout << "value[" << i << "]:" << testVal << std::endl; ++testVal; } }; void run_lambda(std::function<void()> fun){ fun(); fun(); } int main(){ for(int i = 0; i < 3 ; ++i){ lambda l{i}; run_lambda(l); } return 0; } Whilst each iteration of the loop does indeed create a new lambda object each object is an instance of the same class and therefore shares the same static variables. The statement you're quoting is saying that the type is declared inside the scope where the lambda is declared. It isn't saying that each time the code enters that scope a new type is created (c++ doesn't have dynamic types like that).
73,900,598
73,901,691
Why does -fPIC hinder inlining?
I have this foo.cpp: int add(int a, int b) { return a + b; } int add_wrapper(int a, int b) { return add(a,b); } Compiling like so g++ -c -S -fPIC -O4 -finline-functions foo.cpp -o foo.s Gives the (demangled) assembly: .globl add(int, int) .type add(int, int), @function add(int, int): .LFB0: .cfi_startproc endbr64 leal (%rdi,%rsi), %eax ret .cfi_endproc .LFE0: .size add(int, int), .-add(int, int) .p2align 4 .globl add_wrapper(int, int) .type add_wrapper(int, int), @function add_wrapper(int, int): .LFB1: .cfi_startproc endbr64 jmp add(int, int)@PLT .cfi_endproc .LFE1: .size add_wrapper(int, int), .-add_wrapper(int, int) .ident "GCC: (Ubuntu 11.2.0-19ubuntu1) 11.2.0" Note that add() is not inlined. However, without -fPIC, I get .globl add(int, int) .type add(int, int), @function add(int, int): .LFB0: .cfi_startproc endbr64 leal (%rdi,%rsi), %eax ret .cfi_endproc .LFE0: .size add(int, int), .-add(int, int) .p2align 4 .globl add_wrapper(int, int) .type add_wrapper(int, int), @function add_wrapper(int, int): .LFB3: .cfi_startproc endbr64 leal (%rdi,%rsi), %eax ret .cfi_endproc .LFE3: .size add_wrapper(int, int), .-add_wrapper(int, int) With add() inlined. If I add inline to the declaration of add() and compile with -fPIC, I get .globl add_wrapper(int, int) .type add_wrapper(int, int), @function add_wrapper(int, int): .LFB1: .cfi_startproc endbr64 leal (%rdi,%rsi), %eax ret .cfi_endproc .LFE1: .size add_wrapper(int, int), .-add_wrapper(int, int) .ident "GCC: (Ubuntu 11.2.0-19ubuntu1) 11.2.0" With add() omitted entirely. So it seems that inlining is not disallowed by -fPIC because the compiler will inline if I label the function inline, but I don't understand why the compiler is unwilling to inline automatically with '-fPIC'. Does anyone know why this is? Is there a flag that will convince g++ to inline with -fPIC but without labeling functions as inline? I'm using g++ 11.2, but Compiler Explorer shows that the behavior is consistent across versions: https://godbolt.org/z/Y14edz968.
If you add the always_inline attribute to add, you can see the compiler error when it tries to inline: warning: 'always_inline' function might not be inlinable [-Wattributes] 1 | [[gnu::always_inline]] int add(int a, int b) { | ^~~ In function 'int add_wrapper(int, int)': error: inlining failed in call to 'always_inline' 'int add(int, int)': function body can be overwritten at link time note: called from here 6 | return add(a,b); | ~~~^~~~~ The add(int, int) symbol might end up being something else (e.g., another library that was in LD_PRELOAD with an int add(int, int) is loaded first, your add_wrapper should call that one). You can fix this by making add invisible ([[gnu::visibility("hidden")]]) or not giving it external linkage (with an anonymous namespace or static). Or you can make g++ assume this will never happen with the switch -fno-semantic-interposition (which is the default on clang). See New option in GCC 5.3: -fno-semantic-interposition for more information about semantic interposition.
73,900,661
73,939,776
Using swig Python wrapper: argument 2 of type 'std::unordered_set< std::string > const &'
I am updating an old project using (parent project of) the Python package coqui_stt_ctcdecoder generated from C++ using SWIG. Some parameter types in some methods have changed. I am stuck with the method Scorer::fill_dictionary that takes const std::unordered_set<std::string>& as an argument in C++. In the old Python code a list of bytes is passed, but that no longer works, as well as a set. I have no idea what type to put there. The error is Traceback (most recent call last): File "/mnt/d/shared/speech/dsalign/STT-align/align/align.py", line 693, in <module> main() File "/mnt/d/shared/speech/dsalign/STT-align/align/align.py", line 451, in main create_bundle(alphabet_path, scorer_path + '.' + 'lm.binary', scorer_path + '.' + 'vocab-500000.txt', scorer_path, False, 0.931289039105002, 1.1834137581510284) File "/mnt/d/shared/speech/dsalign/STT-align/align/generate_package.py", line 75, in create_bundle scorer.fill_dictionary(words) File "/mnt/d/shared/speech/dsalign/STT-align/venv/lib/python3.10/site-packages/coqui_stt_ctcdecoder/swigwrapper.py", line 1269, in fill_dictionary return _swigwrapper.Scorer_fill_dictionary(self, vocabulary) TypeError: in method 'Scorer_fill_dictionary', argument 2 of type 'std::unordered_set< std::string > const &' EDIT: I have tried a list and a set of str and bytes, all with the above exception. I have used Python 3.8 on Windows and WSL.
SWIG includes support for std::unordered_set, but note that the interface oddly doesn't accept Python set objects. tuple and list work, however. Tested example: test.i %module test // Code injected into wrapper %{ #include <iostream> #include <string> #include <unordered_set> // Function using the parameter type from OP error message void func(std::unordered_set<std::string> const &string_set) { for(auto& s : string_set) std::cout << s << std::endl; } %} // SWIG support for templates %include <std_unordered_set.i> %include <std_string.i> // Must instantiate the specific template used %template(string_set) std::unordered_set<std::string>; // Tell SWIG to wrap the function void func(std::unordered_set<std::string> const &string_set); Demo: >>> import test >>> test.func(['abc','def','abc','ghi']) # list works abc def ghi >>> s = test.string_set(['aaa','bbb','ccc','aaa','bbb']) >>> test.func(s) aaa bbb ccc >>> s = test.string_set(('aaa','bbb','ccc','aaa','bbb')) # tuple works >>> list(s) ['aaa', 'bbb', 'ccc'] >>> test.func({'abc','def'}) # set doesn't work Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\test.py", line 194, in func return _test.func(string_set) TypeError: in method 'func', argument 1 of type 'std::unordered_set< std::string,std::hash< std::string >,std::equal_to< std::string >,std::allocator< std::string > > const &'
73,900,921
73,901,576
Queueuserworkitem vs TrySubmitThreadpoolCallback
Main Question: What is the difference between QueueUserWorkItem and TrySubmitThreadpoolCallback given that they both queue a work item to the Thread Pool TrySubmitThreadpoolCallback This function adds a work item to the thread pool's queue (by calling PostQueuedCompletionStatus) and returns TRUE if successful; it returns FALSE if unsuccessful. In some circumstances, such as lack of memory or quota limitations, the call to TrySubmitThreadpoolCallback might fail. Each time you call TrySubmitThreadpoolCallback, internally a work item is allocated on your behalf. Reference: https://www.amazon.com.br/Windows-Via-C-Jeffrey-Richter/dp/0735663777 QueueUserWorkItem Queues a method for execution where the method executes when the thread is active. Reference: https://www.macoratti.net/09/06/vb_patp.htm As I understand it, both functions do exactly the same thing, is the difference related to compatibility or something along these lines? If not, what is the difference between the two? in addition, if the answer is no, I would like that it is specified the characteristics of each one if possible. WAIT ! If my question is incomplete, or is formatted in an inappropriate way, please comment so I can adjust it, thank you in advance, in advance. Lucas P.
QueueUserWorkItem is from the legacy threadpool API. The newer function gives you more control over the environment in which the callback is executed by virtue of permitting you to initialize an environment for the callback (via InitializeThreadpoolEnvironment). In my experience, when MS starts calling something "legacy" and I have a choice, I find it is usually better to go with the API that is not "legacy"
73,900,929
73,900,980
iso c++ forbids variable length array, didn't understand other question with same topic
I've seen a question on this, but I am not really understanding it as I haven't learned pointers/memory in school, and this is an assignment for school. I'm trying to write a program that takes an integer value from the user, and prints out an upper right triangle with the same leg length. I'm using an array and then storing each cell with a character depending on its coordinates. It's running fine when I compile it, but it doesn't work on my submission. Can someone explain why I'm getting the error in the title? #include <iostream> #include <string> using namespace std; int main() { int size, m, n; cout << "Size"; cin >> size; cout << endl;; const int ARRAY_SIZE = size; string tri_array[(ARRAY_SIZE)][(ARRAY_SIZE)]; for(m = 0; m < size; m++) { for(n = 0; n < size; n++) { if(m > n) { tri_array[m][n] = " "; } else { tri_array[m][n] = "*"; } } } return 0; }
A variable length array is an array whose size is determined at run-time. According to the C++ language, array sizes (capacities) must be determined at compile time. In your code, the capacities are determined at run-time, thus violating the size constraint of an array. Please switch to using std::vector, whose capacity can be set during run-time.
73,900,959
73,901,171
How to create an array of anonymous functions in C++?
C++ has 'lambdas' or anonymous functions. If they do not capture, they can be used in the place of function pointers. I could also declare an array of function pointers as follows: double (*const Trig[])(double) = {sin, cos, tan}; cout << Trig[0](M_PI/2) << endl; // Prints 1 However I cannot figure out the correct syntax to use C++ lamdas in the place of function names in a global array initializer: #include <iostream> using namespace std; static int (*const Func[])(int, int) = { [](int x, int y) -> int { // ^ error: expected expression return x+y; }, [](int x, int y) -> int { return x-y; }, [](int x, int y) -> int { return x*y; }, [](int x, int y) -> int { return x/y; } }; int main(void) { cout << Func[1](4, 6) << endl; } What is the correct way to initialize an array of pointers to anonymous functions in C++? The code is OK. Upgrade your compiler. The result of running g++ --version: Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/usr/include/c++/4.2.1 Apple clang version 12.0.0 (clang-1200.0.32.29) Target: x86_64-apple-darwin19.6.0 Thread model: posix InstalledDir: /Library/Developer/CommandLineTools/usr/bin Compiler error from using g++ /Users/user/Lambda.cpp: /Users/user/Lambda.cpp:4:3: error: expected expression [](int x, int y) -> int { ^ 1 error generated. How can I configure my compiler to accept this code?
The code is correct. The problem was due to the compiler defaulting to an older version of C++, before support for lambda expressions was added in C++11. All I had to do was to tell the compiler to use C++11 (or newer): g++ /Users/user/Lambda.cpp --std=c++11
73,901,480
73,918,135
How to set the correct Intellisense configuration for include path in VS Code?
I am trying to work with Emscripten. I have the compiler set up and working and now I'd like to write some code. However, the include for emscripten remains underlined in red and I can see this error: #include <emscripten/emscripten.h> #include errors detected. Please update your includePath. Squiggles are disabled for this translation unit (D:\MYPROJECT\cpp\main.cpp).C/C++(1696) cannot open source file "emscripten/emscripten.h"C/C++(1696) A "Quick fix" (quotes intended) takes me to the Microsoft C/C++ Extension - IntelliSense Configurations. And there I can edit include paths. I have created a new configuration named EMSCRIPTEN and set these paths: ${workspaceFolder}/cpp/** D:\lib\emsdk\upstream\emscripten\system\include But this has no effect. Now if I do add this to the default configuration that was there from the start (Win32), it works. But I don't want to use that one for my emscripten project! I was kinda hoping to convince to IDE to compile my programs as well. So how do I set per-workspace C++ compiler settings to a given configuration?
Ok, I found it, it's to the right bottom of the screen next to language type selection:
73,901,573
73,901,667
How to have an #ifdef block only evaluate when VS Code intellisense is reading it?
I am working with emscripten, which uses some macros that VS Code IntelliSense does not like. This is not unusual. So what I'd like to do is this: #ifdef INTELLISENSE_IS_READING_THIS #define PROBLEMATIC_MACRO #endif That way, I can keep the macros as is but VS code will stop whining. Sad thing is I remember solving this exact problem in Visual Studio 2017 IntelliSense - with Microsoft's very own resource files - but unfortunately, it appears I did not ask this on stack overflown and instead solved it myself, so now I can't find it anymore.
! Found it. Just needed to craft a query that excludes all the questions about IntelliSense NOT reading or defining defines. This is the way: #ifdef __INTELLISENSE__ #define EMSCRIPTEN_KEEPALIVE #endif And this also works, but may also evaluate in Microsofts compiler: #ifdef _MSC_VER #define EMSCRIPTEN_KEEPALIVE #endif
73,903,038
73,903,064
C++ Bubble Sort Algorithm
I have the following code written in c++ and the algorithm works when in this scenario. I am knew to c++ and don't understand what I did wrong in my 2nd test. #include <iostream> using namespace std; void bubbleSort(int numbers[], int size) { for (int i = 0; i<size;i++) { for (int j=0; j<size;j++) { if (numbers[j] > numbers[j+1]) { swap(numbers[j], numbers[j+1]); } } } } int main() { int numbers[] = {7,5,6,4}; bubbleSort(numbers,4); for (int print = 0; print < 4; print++) { cout << numbers[print] << endl; } return 0; } But, fails when I try to put in numbers that are already sorted: #include <iostream> using namespace std; void bubbleSort(int numbers[], int size) { for (int i = 0; i<size;i++) { for (int j=0; j<size;j++) { if (numbers[j] > numbers[j+1]) { swap(numbers[j], numbers[j+1]); } } } } int main() { int numbers[] = {1,2,3}; bubbleSort(numbers,3); for (int print = 0; print < 3; print++) { cout << numbers[print] << endl; } return 0; }
for (int j=0; j<size;j++) { If size is 3, if the array has three values, for example, this loop iterates with values of j of 0, 1, and 2. if (numbers[j] > numbers[j+1]) { When j is 2 this compares numbers[2] with numbers[3]. There is no numbers[3]. This is undefined behavior. The loop is off by 1 value. Additionally, the overall bubble sort implementation is flawed. In the shown code the inner loop iterates over the entire array (ignoring the off-by-1 bug), every time. In a classical bubble sort the first pass (the first iteration of the outer loop) results in the inner loop iterating over the entire array and "bubbling" the smallest/largest value to the end of the array. On the next pass the inner loop does not need to iterate over the entire array, but only up until the 2nd smallest/largest position of the array. And so on, each pass (the outer loop) results in the inner loop iterating over a smaller, and smaller subset of the array, "bubbling" the corresponding value to the appropriate stop. In addition to fixing the off-by-1 bug you'll also need to adjust the overall logic of this bubble sort, if you wish to get a perfect grade for your homework assignment.
73,903,321
73,903,841
Removal of an Object from a List during iteration
I am trying to make a list of projectile objects that are on screen which execute different methods. This has worked but I keep getting an error when I try to remove the object once it is off screen. std::list<Bullet> bullets; //bullets are added on mouse click //start iterating through objects to move std::list<Bullet>::iterator mover; for (mover = bullets.begin(); mover != bullets.end(); mover++){ //Checks if bullet is off screen if (mover->x < 0 || mover->x > 800 || mover->y < 0 || mover->y > 800) { /* The deconstructor works, but when bullets.erase(mover); is done, a hard exception occurs. I believe it may be due to it iterating to a place with nothing, but I am unsure, and more unsure on how to fix it */ mover->~Bullet(); bullets.erase(mover); std::cout << "Kablooey" << std::endl; //an attempted fix that doesn't seem to do anything if (mover == bullets.end()) { break; } } //makes current object move afterwards, could also be source of error?? //Should I make it check if there is anything there first? mover->Move(); std::cout << "nyoom" << std::endl; } The error says as follows: "Expression: List iterators incompatible". What should I do to make the object be deleted from the list without an error?
Your code has multiple sources of undefined behavior: erase() invalidates the iterator that is passed to it. You are dereferencing and incrementing that iterator after it has been invalidated. erase() returns a new iterator to the next item in the list, you need to continue your loop using that iterator. you are manually destroying objects that you have no business destroying. The list owns the objects and will destroy them when they are erased, or when the list itself is destroyed. Try this instead: std::list<Bullet> bullets; //bullets are added on mouse click ... //start iterating through objects to move std::list<Bullet>::iterator mover = bullets.begin(); while (mover != bullets.end()){ //Checks if bullet is off screen if (mover->x < 0 || mover->x > 800 || mover->y < 0 || mover->y > 800) { mover = bullets.erase(mover); std::cout << "Kablooey" << std::endl; } else { mover->Move(); std::cout << "nyoom" << std::endl; ++mover; } } If you can move std::cout << "Kablooey" << std::endl; into the ~Bullet() destructor, you can then replace the erase loop with a standard algorithm, eg: std::list<Bullet> bullets; //bullets are added on mouse click ... bullets.erase( std::remove_if(bullets.begin(), bullets.end(), [](const Bullet &b){ return (b.x < 0 || b.x > 800 || b.y < 0 || b.y > 800); }, bullets.end() ); /* Alternatively, in C++20: std::erase_if(bullets, [](const Bullet &b){ return (b.x < 0 || b.x > 800 || b.y < 0 || b.y > 800); } ); */ for(auto &b : bullets) { b.Move(); std::cout << "nyoom" << std::endl; }
73,903,328
73,920,434
How can I export a function in C++ using #pragma comment(linker, "/export:...) when the path contains a special character and spaces in it?
I'm trying to create an export by doing the following: #pragma comment(linker, "/export:Breakpad_SetSteamID=C:\\Program Files (x86)\\Steam\\crashhandler64.dll.Breakpad_SetSteamID,@1") But I get the error: 1>dllmain.obj : fatal error LNK1276: invalid directive 'Files' found; does not start with '/' Because the path contains spaces and (x86) in it. How can I achieve this? For example, when I do this: #pragma comment(linker, "/export:WldpIsAppApprovedByPolicy=C:\\Windows\\System32\\wldp.dll.WldpIsAppApprovedByPolicy,@1") I get no errors, because the path is readable. I've been trying to google an answer to this but I cannot find anything. Thank you! Edit: Answered in the comments. For those of you who downvoted my question or questioned why I am using #pragma for this - the answer is ease of use. It's for DLL proxying.
I've found the solution: #pragma comment(linker, "/export:Breakpad_SetSteamID=\"C:\\Program Files (x86)\\Steam\\crashhandler64.dll.Breakpad_SetSteamID\",@1")
73,903,928
73,903,943
Variable 'maxHours' being used without being initialized
So I'm developing a program where I need to get information about what month the user has purchased for a subscription package cellphone plan. Based on the hours of the chosen month and the number of hours the user used within that given month I need to calculate their total costs. My problem arises when I try to use the month that the user had given and assign that month the maxHours in it. For example, January has 31 days therefore it has 744 hours. If they enter a value larger than maxHours, so in this case anything > 744, I want the program to terminate. When using visual studio i get the error "The variable 'maxHours' is being used without being initialized. Although I initialized it following the conditions of the if statements. #include <iostream> using namespace std; int main() { char package; int month; float hours; int maxHours; float extraHoursA = 2.0, extraHoursB = 1.0; float costA, costB, costC; //Supplies the user with the details of each package option cout << "Which package plan did you purchase? Your options are:" << endl; cout << "Package A: For $9.95 per month 10 hours of access are provided. Additional hours are $2.00 per hour." << endl; cout << "Package B: For $14.95 per month 20 hours of access are provided. Additional hours are $1.00 per hour." << endl; cout << "Package C: For $19.95 per unlimited access is provided." << endl << endl; //Asks for the chosen package option cout << "Please enter the letter of your chosen package: "; cin >> package; //Validates the chosen package option if (package != 'a' && package != 'A' && package != 'b' && package != 'B' && package != 'c' && package != 'C') { cout << "You have entered an invalid option, please try again."; return 0; } //Confirms with user the chosen package option else if (package == 'a' || package == 'A'); { cout << endl << "You chose package A. For $9.95 per month 10 hours of access were provided. Additional hours were $2.00 per hour." << endl << endl; } //Asls for the month in which the package was used cout << "Which month did you utilze your plan for? Please enter the month: "; cin >> month; if (month <= 0 || month > 12) { cout << endl << "You have entered an invalid month, please try again."; return 0; } if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 11) { maxHours = 744; } else if (month == 4 || month == 6 || month == 9 || month == 11) { maxHours = 720; } cout << endl << "You utilized the plan in the month of " << month << endl; cout << "How many hours did you use? Please enter the amount of hours you utilized "; cin >> hours; if (hours > maxHours) { cout << "Error: Hours used cannot exceed " << maxHours << " in the " << month << "th month!"; return 0; } if (hours < 0) { cout << "Error: Hours used cannot be less than 0"; return 0; } return 0; }
maxHours is initialized under the if and else if block. If neither of the condition is met, maxHours will stay un-initialized. That is the reason you are getting this error. If you try to print the value of a variable that is not initialized, then you will get a garbage value. Better initialize it with int number At the declaration, do the initialization: int maxHours = 0;
73,904,747
73,904,894
How to reuse CURL and set different doh url at every time in libcurl?
I set the hosts file on PC like this: 127.0.0.1 www.baidu.com Then I wrote a simple test: CURL *curl = curl_easy_init(); for (int i = 0; i < 3; ++i) { if (curl) { curl_easy_setopt(curl, CURLOPT_DNS_CACHE_TIMEOUT, 0L); curl_easy_setopt(curl, CURLOPT_URL, "www.baidu.com"); if (i == 1) curl_easy_setopt(curl, CURLOPT_DOH_URL, "https://dns.alidns.com/dns-query"); else curl_easy_setopt(curl, CURLOPT_DOH_URL, NULL); CURLcode res = curl_easy_perform(curl); std::cout << std::endl; std::cout << "==================================================" << std::endl; std::cout << "Time: " << i << std::endl; std::cout << "res = " << res << std::endl; char *url = NULL; curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url); if (url) printf("Redirect to: %s\n", url); std::cout << "==================================================" << std::endl; curl_easy_reset(curl); } } And the result is like: ================================================== Time: 0 res = 7 Redirect to: http://www.baidu.com/ ================================================== ================================================== Time: 1 res = 0 Redirect to: http://www.baidu.com/ ================================================== ================================================== Time: 2 res = 0 Redirect to: http://www.baidu.com/ ================================================== As defined in CURLcode, r = 0 means CURLE_OK, and r = 7 means CURLE_COULDNT_CONNECT. I don't understand the result. When i == 0, I set DOH_URL to NULL, so it is normal that it couldn't connect. But when i == 2, I also set DOH_URL to NULL, and I do reset operation, and set DNS_CACHE_TIMEOUT to 0, why it still could connect?
curl easy uses the existing connection of the 2nd iteration on the 3rd iteration. See Name Resolving libcurl tries hard to re-use an existing connection rather than to create a new one. The function that checks for an existing connection to use is based purely on the name and is performed before any name resolving is attempted. See curl_easy_reset() It does not change the following information kept in the handle: live connections, the Session ID cache, the DNS cache, the cookies, the shares or the alt-svc cache.
73,904,787
73,904,813
Clang warning on delete pointers
I begin to use clang to replace gcc. But when I delete[] pointers, it gives warning. But when I change, the warning disappears. Why and how to deal with that? int *a = new int[1]; int *b = new int[1]; delete[] a, b; a.cpp:7:17: warning: expression result unused [-Wunused-value] delete[] a, b; int *a = new int[1]; int *b = new int[1]; delete[] a; delete[] b; no warning.
delete[] a, b; is parsed as: (delete[] a), (b); Which you can really think of as: delete[] a; b; In which case it is pretty clear that you're not doing much with b. Where's the warning with GCC? If you use -Wall, gcc will also warn on this since atleast 2007 (gcc 4.1.2): <source>: In function 'int main()': <source>:4:18: warning: right operand of comma operator has no effect [-Wunused-value] 4 | delete[] a, b; | ^ Compiler returned: 0
73,905,902
73,907,632
Initializing struct with json partial information
Supposing a struct A which has 7 member element: struct A { bool m_a; std::string m_b, m_c; float m_d, m_e; double m_f; time_t m_g; A() = default; A( bool a, std::string b, std::string c, float d, float e, double f, time_t g ) : m_a(a), m_b(b), m_c(c), m_d(d), m_e(e), m_f(f), m_g(g) {}; }; And a nlohmann::json where information are stored from the API call: nlohmann::json j = { {"a", "true"}, ... {"g", "1660228853"} }; The API call at best provides all the keys representing the elements of struct A. In case one or more elements are not provided how to initialize the structure efficiently?
Here is a suggestion that is not particularly tuned to high performance (why do you need the efficiency?). It is implemented by overloading from_json from the nlohmann::json library, see here. Because C++ does not have introspection, you must implement a switch statement or several if blocks to map the json keys to your member names. You could maybe contrive a solution using a map and setters, but this is probably overengineered. As for default parameters for your struct, you could either initialize all variables that you do not ever want to be uninitialized in the constructor of A, or you initialize them in the function that creates an instance of A from a json file, or you could leave them uninitialized. This is a bit dangerous, but might be ok for your use case, I don't know. #include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; struct A { bool m_a; std::string m_b, m_c; float m_d, m_e; double m_f; time_t m_g; A() = default; A( bool a, std::string b, std::string c, float d, float e, double f, time_t g ) : m_a(a), m_b(b), m_c(c), m_d(d), m_e(e), m_f(f), m_g(g) {}; }; void from_json(const json& j, A& a) { // set default values for all members if // you don't want uninitialized variables. // Or alternatively initialize all variables // in ctor // overwrite values from json for (auto& [key, value] : j.items()) { if (key == "a") { a.m_a = value; continue; } if (key == "g") { a.m_g = value; continue; } // ... } } int main() { json j = { {"a", true}, {"g", 1660228853} }; A a = j.get<A>(); std::cout << std::boolalpha << a.m_a << std::endl; std::cout << a.m_g << std::endl; // values not contained in j will be uninitialized, // unless you handle them appropriately std::cout << a.m_d << std::endl; } Output: true 1660228853 -7.66069e-28 Give it a go on compiler explorer: https://godbolt.org/z/qaed4P8Kr
73,906,018
73,906,103
Why is the `operation on 'i' may be undefined`and how to fix this warning?
The operation on 'i' may be undefined appears at the second i++ in the line as follows: int i = 4; const uint16_t rawVoltage = (rxBuffer[i++]<<8) | rxBuffer[i++]; I believe it is related to the order of operations, but I guess the parenthesis has priority over the last increment. Btw, the code works fine, as expected, just want to address the warning.
Parentheses affect parsing but not order of evaluation. You have two operations in your expression that modify i: i++ on the left-hand side and i++ on the right-hand side. In general the order of evaluation is not specified in C++. For some operators certain sequencing rules apply, but in particular | does not enforce any sequencing of the two operands. Therefore there is no sequencing rule enforcing any order between the left- and right-hand i++. The standard says that if the value computation or a side effect is unsequenced with another side effect on the same scalar object, then the behavior is undefined. That is the case here on i. The solution is to split the statement into two: uint16_t rawVoltage = (rxBuffer[i++]<<8); rawVoltage |= rxBuffer[i++]; Btw, the code works fine, as expected, just want to address the warning. That's by pure luck. The program has undefined behavior and compilers do make use of that for optimization. Even if it was not undefined behavior the order between the two operands would be unspecified and compilers will also reorder evaluation in such cases if that gives an optimization advantage or they may by default use different orders.
73,906,057
73,906,240
Is it necessary to pay attention to non-error prompts? like no package ‘***’ found?
These prompts exist during the compilation of OPENCV, but no error is reported after the compilation. Generally, if there is no error prompt, I will not pay attention to the information, but I am also worried about it. So, I want to know whether it is necessary to solve these non-error prompts? Thank you. Found OpenEXR: /usr/lib/x86_64-linux-gnu/libIlmImf.so -- Checking for module 'gtk+-3.0' -- Found gtk+-3.0, version 3.22.30 -- Checking for module 'gthread-2.0' -- Found gthread-2.0, version 2.56.4 -- Checking for module 'gstreamer-base-1.0' -- No package 'gstreamer-base-1.0' found -- Checking for module 'gstreamer-video-1.0' -- No package 'gstreamer-video-1.0' found -- Checking for module 'gstreamer-app-1.0' -- No package 'gstreamer-app-1.0' found -- Checking for module 'gstreamer-riff-1.0' -- No package 'gstreamer-riff-1.0' found -- Checking for module 'gstreamer-pbutils-1.0' -- No package 'gstreamer-pbutils-1.0' found -- Checking for module 'gstreamer-base-0.10' -- No package 'gstreamer-base-0.10' found -- Checking for module 'gstreamer-video-0.10' -- No package 'gstreamer-video-0.10' found -- Checking for module 'gstreamer-app-0.10' -- No package 'gstreamer-app-0.10' found -- Checking for module 'gstreamer-riff-0.10' -- No package 'gstreamer-riff-0.10' found -- Checking for module 'gstreamer-pbutils-0.10' -- No package 'gstreamer-pbutils-0.10' found -- Checking for module 'libdc1394-2' -- Found libdc1394-2, version 2.2.5 -- Looking for linux/videodev.h -- Looking for linux/videodev.h - not found -- Looking for linux/videodev2.h ***** ***** -- Could not find OpenBLAS include. Turning OpenBLAS_FOUND off -- Could not find OpenBLAS lib. Turning OpenBLAS_FOUND off -- Could NOT find Atlas (missing: Atlas_CLAPACK_INCLUDE_DIR) -- Looking for dgemm_ -- Looking for dgemm_ - found -- Looking for pthread.h -- Looking for pthread.h - found ******** ******** - The imported target "vtkRenderingPythonTkWidgets" references the file "/usr/lib/x86_64-linux-gnu/libvtkRenderingPythonTkWidgets.so" but this file does not exist. Possible reasons include: * The file was deleted, renamed, or moved to another location. * An install or uninstall procedure did not complete successfully. * The installation package was faulty and contained "/usr/lib/cmake/vtk-6.3/VTKTargets.cmake" but not all the files it references. ********** -- -- Configuring done -- Generating done -- Build files have been written to: /home/timothy/Documents/opencv-3.4.1/build
If you're not familiar with how Configure style scripts work, you're probably quite overwhelmed by what's going on here. These sorts of scripts look for a lot of different dependencies, some optional, some mandatory, and there might be more than one option for each dependency. If something is missing that may or may not be a problem, you need to observe the output carefully and see if it reached the "Done" state, or if it halted early because of a missing dependency. In many cases if it succeeds, you're fine, but a missing dependency may translate to missing features. For example, a missing libpng might mean no PNG support. You'll have to consult the documentation for the implications.
73,906,062
73,906,689
Why does my dynamic array in c++ crash after runtime?
I am trying to make a dynamic array that resizes continuously in runtime In the following code the array should resize on any keypress It works for around three key presses but then suddenly crashes. What is the issue #include<iostream> int main(int argc, char const *argv[]) { std::string b; int size=1; int * a= new int(1); while (true) { std::cin>>b; size++; int *a1=new int(size); for (size_t i = 0; i < size-1; i++) a1[i]=a[i]; delete[] a; a=NULL; a=a1; for (size_t i = 0; i < size; i++) { a[i]=i; std::cout << a[i] << std::endl; } } }
C++ is not obvious, unfortunately. const int count = 3; int* x = new int[count]; // is array of 3 items which values are trash. int* y = new int(count); // is one variable of int equaling 3. If there is array out of bounds, so it is Undefined Behavior in C++. The crash is one of the outcomes. Examples: x[ 0], x[1], x[2];// are well because x has 3 items but x[-1], x[3], x[4];// are UB; // also as y[0]; // it's okey but y[-1], y[1]; // there is the same problem.
73,906,372
73,906,633
Internal Storage and SD Card sector Read/Write for MTP connected android device in C/C++
I want to Read/Write sector (not in File System) from Android device internal storage and SD card. The android device is connected via MTP. Normally, we can use CreateFile/ReadFile/WriteFile API functions for Read/Write sector from DISK in Windows. Also, can use fopen/fread/fwrite functions in Linux. But about the android device which is connected via MTP, I have no experience. If it is possible, please tell me a method. I want to do it using C/C++ in Windows or Linux. Thank you.
What you are asking for is not possible. The whole point of MTP is to abstract away the mass storage aspect and even the file system. You are communicating over a protocol that is based on commands like "copy this file", "what folders are there", etc., and it's up to the device to interpret these commands. Some devices (not Android, but some older handhelds) would even have a layer of file conversion for Office documents while transferring them. This way, the device can keep using its storage while allowing you to access it as well. In the "mass storage device" mode that older Android versions supported, the storage medium had to be unmounted while it was made accessible to the PC. With MTP that does not happen. So, it wouldn't be logical to have a way to modify individual sectors over MTP, as that would clash with the device's file system drivers' authority over the storage medium, and also it would bypass security mechanisms. (Technically, a phone manufacturer could implement a vendor-specific custom command over MTP for accessing sectors, but why would anyone do that?) If you want to know how to access individual files though (using MTP as intended), the keyword you need is Windows Portable Devices. (Not sure about Linux.) The only other way to gain low-level access would be over ADB shell, but that would require a rooted device, otherwise you wouldn't be able to access the storage devices directly from within Android.