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
72,677,835
72,677,893
accessing elements of a vector of struct with iterators c++
I made the following code: namespace bcra { // The value type of a data item. using value_t = long; /// This class represents a single Bar Chart. class BarChart { //=== Definition public: /// Represents a single bar information. struct BarItem { string label; //!< Bar label. value_t value; //!< Bar value. string category; //!< Bar category. BarItem( string l, value_t v, string c ) : label{l}, value{v}, category{c} {/*empty*/} }; //== Data members public: /// The collection of bars items std::vector< BarItem > bars; }; } int main() { BarChart m_barChart; // open file txt m_barChart.bars.push_back(...); // close file txt // .... // .... // .... // creating a vector where I'm going to take a certain range from that main vector. std::vector<BarChart::BarItem> bar_s; for (auto i{ count_value }; i < (count_value + n_linhas); ++i) { bar_s.push_back(m_barChart.bars[i]); } // .... // ... // MY PROBLEM std::vector < value_t>::iterator inicio2; ?????? std::vector<value_t>::iterator fim2; ?????? inicio2 = bar_s.begin(); ???????? // // ... sort(bar_s.begin(), bar_s.end(), compare); my goal is as follows: m_barChart will have all data from a text file with the following structure (string, int, string), and what i want to do is create a new vector where i put a range of this larger vector (so far I've been successful), THE BIG PROBLEM is that i want to get this other vector (bar_s) and sort it with an iterator that goes get the integer value, swapping all objects of bar_s[0] (string, int, string) with bar_s[1] (...), if it is bigger. To do this i need the begin() is only on the integer value (something like => m_bars.begin().value ??) ???? I don't know what to do from here.
This would have been solved by a suitable comparison function in the past but in modern C++ you would use a projection: https://en.cppreference.com/w/cpp/algorithm/ranges/sort
72,679,343
72,679,424
Manjaro Linux cannot open source file "gtkmm.h"
I have been trying to set up my coding environment for GUI development in c++ recently, with little success. I use Manjaro Linux with Visual Studio Code, but for some reason, I always seem to get include errors when including files that I know are there. Most recently, I tried to set up gtkmm-4.0 by installing the package and the documentation. I double checked in /usr/include/ to ensure the packages were all present, but I still am getting include errors: cannot open source file "gtkmm.h" and gtkmm.h:No such file or directory At this point, all the code I have is: #include <gtkmm.h> #include <iostream> int main(int argc, char* argv[]){ return 0; } Makefile: exec = game.out sources = $(wildcard src/*.cpp) objects = $(sources:.cpp=.o) flags = -g $(shell pkg-config gtkmm-4.0 --cflags) libs = $(shell pkg-config gtkmm-4.0 --libs) $(exec): $(objects) g++ $(objects) $(flags) -o $(exec) $(libs) %.o: %.cpp include/%.h g++ -c $(flags) $< -o $@ install: make cp ./game.out /usr/local/bin/game clean: -rm *.out -rm *.o -rm src/*.o I have scoured the internet for answers, but everything I found was either for a different os/environment or just didn't @Galik and @John helped me solve this! What I had to do was use g++ src/main.cpp -o main $(pkg-config gtkmm-4.0 --cflags --libs) to compile my code, then run the executable. Thank you both for your help and guidance!!
You need to install pkg-configand add this to the compiler flags in your Makefile: flags = -g $(shell pkg-config gtkmm-2.4 --cflags) libs = $(shell pkg-config gtkmm-2.4 --libs) # ... $(exec): $(objects) g++ $(objects) $(flags) -o $(exec) $(libs) The tool pkg-config has a database of the correct paths for supporting libraries. Depending on your version if gtkmm, you may need to substitute gtkmm-3.0, if you have version 3.0.
72,679,435
72,680,648
Cmake doesn't move the actual binary when into the install dir when using --install
I'm trying to install a cmake project with cmake --install build --prefix instdir --strip but then instdir has bin, include, and lib but not my actual executable and it's not in any of the folders my CMakeLists.txt looks like cmake_minimum_required(VERSION 3.0.0) project(executionbackup VERSION 0.1.0) # include(CTest) # enable_testing() set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) add_executable(executionbackup main.cpp) set(CPACK_PROJECT_NAME ${PROJECT_NAME}) set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) include(CPack) target_include_directories(executionbackup PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) add_subdirectory(boost-cmake) target_link_libraries(executionbackup PUBLIC Boost::boost) target_link_libraries(executionbackup PUBLIC Boost::program_options) include(FetchContent) FetchContent_Declare(cpr GIT_REPOSITORY https://github.com/libcpr/cpr.git GIT_TAG db351ffbbadc6c4e9239daaa26e9aefa9f0ec82d) FetchContent_MakeAvailable(cpr) target_link_libraries(executionbackup PRIVATE cpr::cpr) FetchContent_Declare(json URL https://github.com/nlohmann/json/releases/download/v3.10.5/json.tar.xz) FetchContent_MakeAvailable(json) target_link_libraries(executionbackup PRIVATE nlohmann_json::nlohmann_json) # get spdlog through FetchContent FetchContent_Declare(spdlog GIT_REPOSITORY https://github.com/gabime/spdlog.git GIT_TAG v1.10.0) FetchContent_MakeAvailable(spdlog) target_link_libraries(executionbackup PRIVATE spdlog::spdlog)
Adding install(TARGETS executionbackup DESTINATION bin) to the end of my CMakeLists.txt worked.
72,679,649
72,679,710
A lambda with a capture fail to compile when used with std::semi_regular
The following example fails to compile as soon as the lambda capture any variable. If the capture is removed the compiler will successfully compile the code below. #include <concepts> #include <functional> #include <iostream> template<typename T> concept OperatorLike = requires(T t, std::string s) { { t[s] } -> std::same_as<std::string>; }; template<typename T, typename O> concept Gettable = requires(T t, O op) { t.apply_post(0, op); }; template<std::semiregular F> class RestApiImpl { F m_post_method; public: RestApiImpl(F get = F{}) : m_post_method{std::move(get)} {} template<OperatorLike IF> requires std::invocable<F, const int, IF> void apply_post(const int req, IF interface){ m_post_method(req, std::move(interface)); } }; int main(){ int ii; auto get = [&ii](int, OperatorLike auto intf){ std::string dummy = "dummy"; std::cout << intf[dummy]; }; RestApiImpl api(get); return 0; }; If the lambda function get() has empty brackets [] , meaning no capture it will compile. The need of the class RestApiImpl is based on following application: class Server{ public: struct impl; void run(Gettable<impl> auto& api){ api.apply_post(0, impl(*this)); } struct impl { public: Server& m_server; impl(Server& server ) : m_server(server){} std::string operator[](std::string key) { return "dummy_for_now"; } }; }; int main(){ auto get = [&ii](int, OperatorLike auto intf){ std::string dummy = "dummy"; std::cout << intf[dummy]; }; RestApiImpl api(get); Server server; server.run(api); return 0; }; The error message: :35:24: error: class template argument deduction failed: 35 | RestApiImpl api(get); | ^ :35:24: error: no matching function for call to 'RestApiImpl(main()::&)' :18:5: note: candidate: 'template RestApiImpl(F)-> RestApiImpl' 18 | RestApiImpl(F get = F{}) : m_post_method{std::move(get)} {} | ^~~~~~~~~~~ :18:5: note: template argument deduction/substitution failed: : In substitution of 'template RestApiImpl(F)-> RestApiImpl [with F = main()::]': :35:24: required from here :18:5: error: template constraint failure for 'template requires semiregular class RestApiImpl' :18:5: note: constraints not satisfied What options to I have in terms of overcoming this ?`
std::semiregular requires both std::copyable and std::default_initializable. std::copyable means that it requires the type to be copy-constructible and copy-assignable. std::default_initializable means that it requires the type T to have well-formed initializations of the forms T t;, T() and T{}. A lambda with a capture has a deleted copy assignment operator, no move assignment operator and no default constructor, while for a capture-less lambda (since C++20) all of them are defaulted. As a consequence a lambda with capture is not std::copyable (or std::movable for that matter) and not std::default_initializable and so especially also not std::semiregular, while a capture-less lambda is all of these. Your RestApiImpl requires that the passed argument for F get in the constructor be std::semiregular. To resolve this rethink whether RestApiImpl really requires all of these properties of the type. I can see that it requires move-constructibility in m_post_method{std::move(get)}, but it is unclear where it uses e.g. copy-assignability from what you are showing. = F{} uses default-constructibility, but that default value is not used or instantiated if you are not default-constructing a RestApiImpl instance with that type. Then use concepts which are not as restrictive as std::semiregular. If that is not a possibility, then you cannot use a lambda like this directly. Instead you can use an old-style functor type, e.g. a class with overloaded operator() and have it store a std::reference_wrapper<int> to the ii object. This assures assignability, because a simple reference as member would make the class non-assignable.
72,679,871
72,679,892
Enqueue successful, but Queue prints nothing?
I am trying to enqueue data into a queue. The enqueue appears to have been successful because the current Node's Thing pointer is not null. Indeed, its Thing id is 7 as expected. However, something is wrong with ThingQueue's print function because the exact same Node is identified as a nullptr. This is despite the fact that both the enqueue and print functions iterate through the queue in the same way. Can anybody explain the discrepancy? Here is a minimal reproducible example of my problem: #include <iostream> using namespace std; struct Thing { int id; Thing() { id = 7; } void print() { cout << "Thing " << to_string(id) << " "; } }; class ThingQueue { public: ThingQueue() { front = nullptr; } void enqueue(const Thing &thing) { cout << "Attempting to enqueue..." << endl; Node *curr = front; while (curr != nullptr) curr = curr->next; curr = new Node; curr->next = nullptr; curr->thing = (Thing*) &thing; cout << "Is curr->thing nullptr? 1 for true, 0 for false: "; cout << to_string(curr->thing == nullptr) << endl; cout << "curr->thing->id = " << to_string(curr->thing->id) << endl; } void print() { cout << "Attempting to print..." << endl; Node *curr = front; cout << "Is curr nullptr? 1 for true, 0 for false: "; cout << to_string(curr == nullptr) << endl; while (curr != nullptr) { curr->thing->print(); curr = curr->next; } } private: struct Node { Node *next; Thing *thing; }; Node *front; }; int main() { Thing *pThing = new Thing(); ThingQueue *pThingQueue = new ThingQueue(); pThingQueue->enqueue(*pThing); pThingQueue->print(); std::cout << std::endl; return 0; } Output: Attempting to enqueue... Is curr->thing nullptr? 1 for true, 0 for false: 0 curr->thing->id = 7 Attempting to print... Is curr nullptr? 1 for true, 0 for false: 1 SOLUTION: Thanks for all the tips and feedback. After working out the remaining bugs and feedback, I have a minimum reproducible example that compiles, runs and produces the expected output! (Not worrying about memory management for this example) #include <iostream> using namespace std; struct Thing { int id; Thing() { id = 7; } void print() { cout << "Thing " << to_string(id) << " "; } }; class ThingQueue { public: ThingQueue() { front = nullptr; } void enqueue(const Thing &thing) { if (front == nullptr) { // queue is empty, set front to new node front = new Node; front->next = nullptr; front->thing = thing; } else { // queue is not empty, find last node Node* curr = front; while (curr->next != nullptr) curr = curr->next; // curr now points to the last node, set curr->next to new node curr->next = new Node; curr->next->next = nullptr; curr->next->thing = thing; } } void print() { Node *curr = front; while (curr != nullptr) { curr->thing.print(); curr = curr->next; } } private: struct Node { Node *next; Thing thing; }; Node *front; }; class Stuff { }; int main() { Thing thing = Thing(); Thing thing2 = Thing(); Thing thing3 = Thing(); ThingQueue tq = ThingQueue(); tq.enqueue(thing); tq.enqueue(thing2); tq.enqueue(thing3); tq.print(); return 0; }
Look at enqueue, it creates a new Node and sets curr to point at it. But curr is a variable in the enqueue function, it has nothing to do with your queue, as soon as the enqueue function is exited the curr variable is lost. You also have another problem. For some reason you have made thing a pointer. This means you end up with pointers to variables which have been destroyed. Change thing to be a non-pointer. Here's how enqueue should look. void enqueue(const Thing &thing) { if (front == nullptr) { // queue is empty, set front to new node front = new Node; front->next = nullptr; front->thing = thing; } else { // queue is not empty, find last node Node* curr = front; while (curr->next != null) curr = curr->next; // curr now points to the last node, set curr->next to new node curr->next = new Node; curr->next->next = nullptr; curr->next->thing = thing; } } I can see you are suffering from the pointers everywhere syndrome that beginners sometimes have. Here's main rewritten without all the unnecessary pointers int main() { Thing thing; ThingQueue thingQueue; thingQueue.enqueue(thing); thingQueue.print(); std::cout << std::endl; return 0; } The only pointers you need in this code are the next field in your node class, the front member in your queue class, and the curr variable.
72,680,155
72,680,214
Explicitly defaulted copy/move assignment operators implicitly deleted because field has no copy/move operators. C++
I'm new to C++ and dont know why this is happening and how to fix it. Here's some snippets of the code: header file: class Dictionary{ private: string filename; const string theSeparators; public: Dictionary(const string& filename, const string& separators = "\t\n"); Dictionary() = delete; ~Dictionary() = default; Dictionary(const Dictionary&) = default; Dictionary(Dictionary&&) = default; Dictionary& operator=(const Dictionary&) = default; Dictionary& operator=(Dictionary&&) = default; }; cpp file: Dictionary::Dictionary(const string& filename, const string& separators = "\t\n"){ /* some stuff for the filename*/ } error: copy assignment operator of 'Dictionary' is implicitly deleted because field 'theSeparators' has no copy assignment operator const string theSeparators; error:move assignment operator of 'Dictionary' is implicitly deleted because field 'theSeparators' has no move assignment operator const string theSeparators;
This data member const string theSeparators; is defined with the qualifier const. So it can not be reassigned after its initialization in a constructor. Thus the compiler defined the copy and move assignment operators as deleted. You can just remove the qualifier const for this data member. Or if to keep the qualifier const for the data member then you have to use mem-initialing lists in constructors like for example Dictionary::Dictionary(const string& filename, const string& separators = "\t\n") : filename( filename ), theSeparators( separators ) { //... } But in this case the copy and move assignment operators will be still deleted.
72,680,159
72,692,985
How do you properly overwrite instructions loaded in memory from an injected DLL?
I am writing a dynamic link library to be injected into a singleplayer game on Windows and serve as a "cinematic tool" (overwriting camera transforms, timescale, etc.): Let's say that the base address for the game executable in the virtual memory space is 0x140000000 and there's an instruction at foo.exe+0x10D64B81 that I want to overwrite. The instruction is mulss xmm1,[rdi+0000027C] (F3 0F 59 8F 7C 02 00 00, 8 bytes), the modified code to be written starting at that address/offset is xorps xmm1,xmm1 / nop / nop / nop / nop / nop (0F 57 C9 90 90 90 90 90, 8 bytes). I have the following implementation (simplified for demonstration purposes): #include <Windows.h> using byte = unsigned char; class FunctionMod { public: FunctionMod(void* baseAddress, size_t offset, const byte* code, size_t length) : m_BaseAddress(baseAddress), m_Offset(offset), m_ModifiedCode(), m_Length(length) { m_ModifiedCode = new byte[m_Length]; std::copy(code, &code[m_Length], m_ModifiedCode); } ~FunctionMod() noexcept { delete[] m_ModifiedCode; } void overwrite() const { for (size_t i = 0; i < m_Length; i++) *((byte*)m_BaseAddress + m_Offset + i) = m_ModifiedCode[i]; } private: void* m_BaseAddress; size_t m_Offset; size_t m_Length; byte* m_ModifiedCode; }; ... DWORD64 functionOffset = 0x10D64B81; byte functionCode[8] = { 0x0F, 0x57, 0xC9, 0x90, 0x90, 0x90, 0x90, 0x90 }; FunctionMod guiMod( (void*)GetModuleHandle(NULL), functionOffset, functionCode, sizeof(functionCode) ); guiMod.overwrite(); This works perfectly fine with other offsets and instructions, but for some reason, this particular example consistently writes 0F **A2** C9 90 ... to the respective memory location, instead of 0F **57** C9 90 ..., translating to cpuid \ leave \ nop ... and thus crashing the process. I'm losing my mind trying to figure out what I'm doing wrong. There doesn't seem to be a point where 0x57 could somehow become 0xA2. I have verified that the memory is copied correctly in the class constructor, printing out the bytes to a console instead of writing them to the actual memory also gives the expected result, the pointer arithmetic checks out as well. The only time the 0xA2 is written is when I dereference the pointer and write to the actual memory. Anyone, please, any ideas? EDIT: Overwriting the memory from a different process running as administrator with WriteProcessMemory works properly, but I "need" (it would be much less work) to do this from the dll.
Pausing and resuming threads Thanks to @CherryDT for pointing this out — suspending the other threads of the process before writing to memory and then resuming them did the trick. The function whose instructions I'm overwriting is one that calculates and modifies HUD opacity. In hindsight, it seems kind of obvious that a function like this would be called very often (probably in the game loop, so at least once per every frame) and so my hypothesis is that one of the game threads probably got to the function while my thread was still writing to that memory region, therefore encountering invalid instructions and stopping execution. I still don't know why the magical A2 byte appeared every time, but even when I tried writing different instructions or changed their order (which, strangely, wrote the bytes I wanted correctly), I still got a crash afterwards. Hence the solution: void FunctionMod::overwrite() const { pauseThreads(); for (size_t i = 0; i < m_Length; i++) *((byte*)m_BaseAddress + m_Offset + i) = m_ModifiedCode[i]; flushInstructionCache(); // in my experience not necessary but better be safe than sorry resumeThreads(); } where both pauseThreads and resumeThreads first get a list of thread ids using Toolhelp32 as decribed here (make sure to exclude the id of the calling thread, i.e. GetCurrentThreadId()) and then use OpenThread with the THREAD_SUSPEND_RESUME access flag to get the thread handles and finally SuspendThread and ResumeThread to pause and resume thread execution. Phew!
72,680,740
72,680,754
Invalid argument STD error after compiling - no errors in VS Code IDE
I need some help with a simple program I am writing to get output from the /sys/class/thermal/thermal_zone0/temp file. Ordinarily using the command cat /sys/class/thermal/thermal_zone0/temp outputs the temperature as a five digit integer (i.e. 45000). The intention of my program is to take that output and convert it to human readable in degrees Celsius, degrees Fahrenheit, and Kelvin. One of the instructions in the code is to take the sysTemp variable which will be read in as a string and convert it to a double called tempLong named because it will contain the original read in from the /sys/class/thermal/thermal_zone0/temp file. From there a little math conversions take place to output to the user temperature data in the three aforementioned formats. This is where I believe the error is originating from. Showing no errors in VS Code. After compiling in Linux using g++ (version 9.4.0) the program will not run. Instead I get the following error (I included the command I used to compile): $ g++ -o tempmon Repositories/TemperatureMonitor/src/tempmonCPU.cpp $ ./tempmon terminate called after throwing an instance of 'std::invalid_argument' what(): stod Aborted (core dumped) Here is my code: // Preprocessor directives and namespace usage #include <iostream> #include <iomanip> #include <fstream> #include <string> using namespace std; // Main function int main() { ifstream thermal; string sysTemp = ""; // Will store the output of thermal double tempLong = stod(sysTemp); // Convert string to double double tempCelsius = tempLong / 1000; // Convert output to human readable double tempFahrenheit = tempCelsius * (9/5) + 32; // Convert to Fahrenheit double tempKelvin = tempCelsius + 273.15; // Convert to Kelvin setprecision(3); // Use 3 significant digits // Read in /sys/.../temp file // Point read pointer to beginning of file thermal.open ("/sys/class/thermal/thermal_zone0/temp", ios::in); // Check if file is open and output in human readable format if (thermal.is_open()) { while (getline (thermal, sysTemp)) { // Output to human readable format cout << " System temperature (Celsius): " << tempCelsius << " \u00B0C\n" << "System temperature (Fahrenheit): " << tempFahrenheit << " \u00B0F\n" << " System temperature (Kelvin): " << tempKelvin << " K\n"; } thermal.close(); } else // File does not open { cout << "Failure to open '/sys/class/thermal/thermal_zone0/temp'\n" << "Please try again . . .\n\n"; } // Exit program without errors return 0; } Code can also be found at my GitHub: https://github.com/kawilkins/TemperatureMonitor I am absolutely certain I jacked up some syntax somewhere. File I/O I applied pretty much from memory, except for a few sanity checks to make sure I was remembering the syntax correctly. At this point any help would be appreciated.
Variables in C++ will not automatically updated like wire in Verilog. Do the conversion after reading lines. // Preprocessor directives and namespace usage #include <iostream> #include <iomanip> #include <fstream> #include <string> using namespace std; // Main function int main() { ifstream thermal; string sysTemp = ""; // Will store the output of thermal // do not do conversion here //double tempLong = stod(sysTemp); // Convert string to double //double tempCelsius = tempLong / 1000; // Convert output to human readable //double tempFahrenheit = tempCelsius * (9/5) + 32; // Convert to Fahrenheit //double tempKelvin = tempCelsius + 273.15; // Convert to Kelvin setprecision(3); // Use 3 significant digits // Read in /sys/.../temp file // Point read pointer to beginning of file thermal.open ("/sys/class/thermal/thermal_zone0/temp", ios::in); // Check if file is open and output in human readable format if (thermal.is_open()) { while (getline (thermal, sysTemp)) { // do conversion here double tempLong = stod(sysTemp); // Convert string to double double tempCelsius = tempLong / 1000; // Convert output to human readable double tempFahrenheit = tempCelsius * (9/5) + 32; // Convert to Fahrenheit double tempKelvin = tempCelsius + 273.15; // Convert to Kelvin // Output to human readable format cout << " System temperature (Celsius): " << tempCelsius << " \u00B0C\n" << "System temperature (Fahrenheit): " << tempFahrenheit << " \u00B0F\n" << " System temperature (Kelvin): " << tempKelvin << " K\n"; } thermal.close(); } else // File does not open { cout << "Failure to open '/sys/class/thermal/thermal_zone0/temp'\n" << "Please try again . . .\n\n"; } // Exit program without errors return 0; }
72,680,962
72,680,973
Video frame returning !_src.empty() in function 'cvtColor' error
I am trying to convert frames from a video to Tensors as the video is playing. This is my code: #include <iostream> #include "src/VideoProcessing.h" #include <opencv2/opencv.hpp> #include <opencv2/videoio.hpp> typedef cv::Point3_<float> Pixel; const uint WIDTH = 224; const uint HEIGHT = 224; const uint CHANNEL = 3; const uint OUTDIM = 128; void normalize(Pixel &pixel){ pixel.x = (pixel.x / 255.0 - 0.5) * 2.0; pixel.y = (pixel.y / 255.0 - 0.5) * 2.0; pixel.z = (pixel.z / 255.0 - 0.5) * 2.0; } int main() { int fps = VideoProcessing::getFPS("trainer.mp4"); unsigned long size = VideoProcessing::getSize("trainer.mp4"); cv::VideoCapture cap("trainer.mp4"); //Check if input video exists if(!cap.isOpened()){ std::cout<<"Error opening video stream or file"<<std::endl; return -1; } //Create a window to show input video cv::namedWindow("input video", cv::WINDOW_NORMAL); //Keep playing video until video is completed while(true){ cv::Mat frame; frame.convertTo(frame, CV_32FC3); cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB); // convert to float; BGR -> RGB // normalize to -1 & 1 auto* pixel = frame.ptr<Pixel>(0,0); const Pixel* endPixel = pixel + frame.cols * frame.rows; for (; pixel != endPixel; pixel++){normalize(*pixel);} // resize image as model input cv::resize(frame, frame, cv::Size(WIDTH, HEIGHT)); //Capture frame by frame bool success = cap.read(frame); //If frame is empty then break the loop if (!success){ std::cout << "Found the end of the video" << std::endl; break; } //Show the current frame cv::imshow("input video", frame); if (cv::waitKey(10) == 27){ std::cout << "Esc key is pressed by user. Stopping the video" << std::endl; break; } } //Close window after input video is completed cap.release(); //Destroy all the opened windows cv::destroyAllWindows(); std::cout << "Video file FPS: " << fps << std::endl; std::cout << "Video file size: " << size << std::endl; return 0; } My goal (down the road) is to run inference on each frame to get landmarks. However, at this stage, I see this error: terminate called after throwing an instance of 'cv::Exception' what(): OpenCV(4.1.0) /home/onur/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor' Aborted (core dumped) Where am I going wrong?
You will have to read the frame before performing any conversion. Move the part //Capture frame by frame bool success = cap.read(frame); //If frame is empty then break the loop if (!success){ std::cout << "Found the end of the video" << std::endl; break; } Just after cv::Mat frame;
72,681,360
72,682,148
How C++ call parameterized ctor to create object arrays?
I know in c++11 I can use initializer to create array/vector elements one by one like: int ar[10]={1,2,3,4,5,6}; vector<int> vi = {1,2,3,4}; This is done manually, but what if I wish to initialize an array/vector with 10000 elements and specify their value, can it be done in one statement, RAII pattern? E.g. I've defined a class: class Somebody{ int age; string name; public: Somebody():age(20),name("dummy"){} // default ctor Somebody(int a, const char* n):age(a),name(n){} // but I wish to call this ctor Somebody& operator = (const Somebody& s) {...} }; Then in main function: int main(int argc, char const *argv[]) { Somebody obj(2, "John"); // parameterized ctor Somebody ar[300]; // initialized, but called default ctor for(int i=0;i<300;++i){ // initialize again in a loop ar[i] = ... ; // call operator = ... Question: could Somebody ar[300] be constructed with parameterized ctor? If not, then I have to create this object array ar first(Compiler generated code will loop and call default parameter), then apply value changes for each object. This seems quite a bit redundant of cpu cycles. Is there a way to do what I expected with just one call? (Loop and update each array element with parameterized ctor) Thanks.
You can not do this with C-style arrays. One of the many reasons you should not be using them in the first place. You should be using std::vector, which provides a constructor to populate the vector using a single value: std::vector<Somebody> ar{300, Somebody("42", "filler")}; But often it is better to not create such dummy entries in the first place. A std::vector can grow dynamically so you can just add Somebody objects to it as you get their age and name. std::vector people; people.reserve(2); // optional but makes adding lots of objects more efficient Somebody adam(42, "Adam"); people.push_back(adam); people.emplace_back(23, "Eve"); This shows you 2 ways to add objects to the vector, the push_back adds objects to the vector (copies/moves it) while emplace_back will construct the object directly in the vector, which is often more efficient. If you want a fixed size array then you can use std::array<Somebody, 300> ar; ar.fill(Somebody(23, "filler")); But this has the same problem as the C-style array of using the default construtor. std::arrays::fill replaces all the objects with a new value. Unfortunately there is no array constructor to do this in one go which is rather unfortunate.
72,682,129
72,683,466
Does initializing references cost more memory if you copy to an lvalue less than the size of a reference?
So I believe on 64-bit systems a pointer is 8B. A float is 4B. Let's say you have the following code: const float a = 1.0f; Then, I want to know the cost comparison of the following. Say we have const float b = a; I know that copying float will be 4B. But I would think that we can 'save' memory if we don't have to copy the float. I know that if it weren't float, but instead a large object (>8B), using a reference in a similar manner would be more optimal: const float &b = a; However, since we are using float, is it more compact to copy to a new variable? Assuming that the compiler won't optimize anything? const float a = b; const float &a = b;
If you write const float b = a; then you are making a copy of the value. Now if the type is a fundamental type or trivially copyable with no custom copy constructor the compiler can easily optimize away the copy and no actual code gets generated at all. That is unless you take the address of the obejct: #include <iostream> int main() { const float a = 1.0; const float b = a; const float &r = a; std::cout << "&a == &b: " << (&a == &b ? "true" : "false") << std::endl; std::cout << "&a == &r: " << (&a == &r ? "true" : "false") << std::endl; } gives: &a == &b: false &a == &r: true As you can see a and b have different addresses. They are different objects and the compiler will have to add a copy of a named b. The reference r on the other hand is the same object as a so it has the same address. The compiler will not make a copy. This also holds if a isn't a trivial type and the compiler can't eliminate the copy constructor. The reference is a total NOP, it just gives the existing object another name. But don't confuse this with passing values by reference or storing references in structs or classes. Internally a reference is implemented as a pointer. If you pass a reference then you pass a copy of the pointer. If you store a reference then the pointer is stored. Only for local references the compiler can use the original object directly.
72,682,461
72,702,302
Reading android asset file by JNI C++ is failed
I have made android app with jni C++ code. To read model file while creating apk on android native code(C++), I placed the model file in assets folder. (so file path is my_app/src/main/assets/model.tflite) Then, I tried to read the model with following code but an error has raised: Kotlin code: private val context: Context get() = getApplication<Application>().applicationContext asset_manager = context.assets C++ code: AAssetManager* mgr = AAssetManager_fromJava(env, asset_manager); AAssetDir* assetDir = AAssetManager_openDir(mgr, ""); const char* filename = (const char*)NULL; while ((filename = AAssetDir_getNextFileName(assetDir)) != NULL) { AAsset* asset = AAssetManager_open(mgr, filename, AASSET_MODE_STREAMING); __android_log_print(ANDROID_LOG_INFO, "tag", "file name is: %s", filename); <- file name reading is ok char buf[BUFSIZ]; int nb_read = 0; FILE* out = fopen(filename, "w"); <- out has null FILE* while ((nb_read = AAsset_read(asset, buf, BUFSIZ)) > 0) fwrite(buf, nb_read, 1, out); fclose(out); AAsset_close(asset); } AAssetDir_close(assetDir); logcat : 2022-06-19 22:45:54.449 12180-12180/com.my.first.app I/tag: file name is: model.tflite 2022-06-19 22:45:54.449 12180-12180/com.my.first.app A/libc: FORTIFY: fwrite: null FILE* 2022-06-19 22:45:54.450 12180-12180/com.my.first.app A/libc: Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 12180 (st.app), pid 12180 (st.app) Why does fopen(filename, "w") return null? It seems that AAssetManager is work.
Thanks to @Botje, I can load the model.tflite in assets by this way: AAssetManager* mgr = AAssetManager_fromJava(env, asset_manager); AAssetDir* assetDir = AAssetManager_openDir(mgr, ""); const char* filename = nullptr; while ((filename = AAssetDir_getNextFileName(assetDir)) != nullptr) { AAsset* asset = AAssetManager_open(mgr, filename, AASSET_MODE_STREAMING); size_t size = AAsset_getLength(asset); buf = new char[size]; memmove(buf, AAsset_getBuffer(asset), size); AAsset_close(asset); } AAssetDir_close(assetDir); std::unique_ptr<tflite::FlatBufferModel> model = tflite::FlatBufferModel::BuildFromBuffer((const char*)buf, size); std::unique_ptr<tflite::Interpreter> interpreter; tflite::ops::builtin::BuiltinOpResolver op_resolver; tflite::InterpreterBuilder(*model, op_resolver)(&interpreter);
72,682,547
72,682,630
Is there a method to let #define normal literals as essential operators of C++?
Problem Description I participate in competitive programming. Given that I am in desperate need of an essential template to memorize, I use macros very much. For instance, I use #define large long long large value; There are two operators that I am annoyed of though: << and >> as of input and output. Expectation I would like to see something like #include <iostream> using namespace std; #define and << #define with >> #define print cout #define input cin int main() { long long value1, value2; input value1 with value2; print value1 and value2; } I expect this program to echo two integral values that the user inputs. Issue However, I constantly receive an error stating that Cannot #define something as an operator. How do I resolve that? If I cannot, is there a replacement to #define and <<? I absolutely appreciate your response.
It is perfectly legal (though nauseous) to have a macro that expands to an operator such as << or >>, example. You just can't use and as the name of your macro, since and is a keyword. So if you insist on going this route, just choose some other name that isn't on the list of keywords.
72,682,866
72,683,792
How to Multi-Client in UDP socket communication
I want to have multiple clients connect, and I want to do recvfrom and sendto. I have used std:vector as follows, but every time I recvfrom, I put information, so I wrote an if statement, but '==' gets an error.(no operator == matches these operands) Is there a way not to add it to the vector when the same client 'recvfrom'? std::vector<SOCKADDR_IN> udpClient_list; addrlength = sizeof(dlg->client_addr); recv_size = recvfrom(dlg->server_sock, reinterpret_cast<char*>(buf), BUFFER_SIZE, 0, (SOCKADDR*)&dlg->client_addr, &addrlength); for (int i = 0; i == udpClient_list.size(); i++) { if (udpClient_list[i] != &dlg->client_addr) { udpClient_list.push_back(dlg->client_addr); break; } }
First, your loop condition is wrong. i should be size_t, and you need to use < instead of == when comparing i to udpClient_list.size(). Second, you are comparing a SOCKADDR_IN instance to a SOCKADDR_IN* pointer, which obviously won't work. Get rid of &. But even then, you can't compare SOCKADDR_IN instances using operator== unless you manually define that operator yourself. Third, you need to add a new entry to the vector only if ALL of the existing entries don't match. But you are adding the new entry if ANY entry doesn't match. Try something more like this: bool operator==(const SOCKADDR_IN &addr1, const SOCKADDR_IN &addr2) { return (addr1.sin_family == AF_INET && addr1.sin_family == addr2.sin_family && addr1.sin_port == addr2.sin_port && addr1.sin_addr.s_addr == addr2.sin_addr.s_addr); } std::vector<SOCKADDR_IN> udpClient_list; ... addrlength = sizeof(dlg->client_addr); recv_size = recvfrom(dlg->server_sock, reinterpret_cast<char*>(buf), BUFFER_SIZE, 0, (SOCKADDR*)&dlg->client_addr, &addrlength); if (recv_size < 0) ... // error handling bool exists = false; for (size_t i = 0; i < udpClient_list.size(); ++i) { if (udpClient_list[i] == dlg->client_addr) { exists = true; break; } } if (!exists) udpClient_list.push_back(dlg->client_addr); With that said, consider using std::find() instead, eg: bool operator==(const SOCKADDR_IN &addr1, const SOCKADDR_IN &addr2) { return (addr1.sin_family == AF_INET && addr1.sin_family == addr2.sin_family && addr1.sin_port == addr2.sin_port && addr1.sin_addr.s_addr == addr2.sin_addr.s_addr); } std::vector<SOCKADDR_IN> udpClient_list; ... addrlength = sizeof(dlg->client_addr); recv_size = recvfrom(dlg->server_sock, reinterpret_cast<char*>(buf), BUFFER_SIZE, 0, (SOCKADDR*)&dlg->client_addr, &addrlength); if (recv_size < 0) ... // error handling if (std::find(udpClient_list.begin(), udpClient_list.end(), dlg->client_addr) == udpClient_list.end()) udpClient_list.push_back(dlg->client_addr);
72,682,905
72,683,087
last character of character array is getting excluded
#include<iostream> using namespace std; int main() { int n; cin>>n; cin.ignore(); char arr[n+1]; cin.getline(arr,n); cin.ignore(); cout<<arr; return 0; } Input: 11 of the year Output: of the yea I'm already providing n+1 for the null character. Then why is the last character getting excluded?
You allocated n+1 characters for your array, but then you told getline that there were only n characters available. It should be like this: int n; cin>>n; cin.ignore(); char arr[n+1]; cin.getline(arr,n+1); // change here cin.ignore(); cout<<arr;
72,683,577
72,683,730
Checking if vector passes through vertices c++
How can I check if a vector that starts at one point passes through another one point? It is on two-dimensional coordinates. Mainly uses c ++, but other languages are possible. float2 startToTarget = target - start; if ((startToTarget.x) * vec.y - (startToTarget.y) * vec.x >= -floatingPoint && (startToTarget.x) * vec.y - (startToTarget.y) * vec.x <= floatingPoint) if ((startToTarget.x) * vec.x + (startToTarget.y) * vec.y >= -floatingPoint && (startToTarget.x) * vec.x + (startToTarget.y) * vec.y <= floatingPoint) intersecting = true;
Calculate cross product of vector d (direction) and AB vector. If result is zero, then these vectors are collinear, so B point lies on the line, defined by point A and direction vector d. To check direction, evaluate also dot product, it's sign is positive, when direction d coincides with direction AB abx = B.x - A.x; aby = B.y - A.y; //cross product //dot product if (abs(abx*dy - aby*dx) < 1.0e-10 and abx*dx + aby*dy>0) {B lies on the ray A+d}
72,684,588
72,685,104
How to solve the problem that the subclass inherits the base class and meanwhile the base class is a template parameter
#include <iostream> using namespace std; template <typename Child> struct Base { void interface() { static_cast<Child*>(this)->implementation(); } }; template<typename T, template<class T> class Base > struct Derived : Base<Derived > { void implementation(T t=0) { t = 0; cerr << "Derived implementation----" << t; } }; int main() { Derived<int,Base<Derived>> d; //Base class as a template parameter is must d.interface(); // Prints "Derived implementation" return 0; } I hope Derived class inherits from a template parameter Base class,meanwhile hope the instance of Base class depend on Derived class, the Derived class have another template parameter T,I have tried many ways but can't solve it . Base class as a template parameter is must I have simplified the source code, but these conditions I describe are necessary. Now I hope that under these conditions I describe, I can call the interface() sucessfully Does anyone know where the problem is and how to fix it?
template<typename T, template <typename> typename Base> struct Derived : Base<Derived<T, Base>> { void implementation(T t=0) { t = 0; cerr << "Derived implementation----" << t; } }; Derived<int, Base> d; d.interface(); // Prints "Derived implementation" Online Demo
72,686,164
72,686,240
Doubts about the auto keyword type deduction in C++
Here is a code snippet I have created: auto f = [](auto a) -> auto { cout << a << endl; return a; }; cout << f(12) << endl; cout << f("test"); Here is what I know: Types have to be all resolved / specified at compile time. The question here is, how is the compiler behaving when it sees this lambda function f? How does it deduces all the types for specific use like in line 6 and 7, in which we can see there are two different arguments passed for each call of lambda function f. Is the compiler creating different instances of the lambda function f to match the types passed? Any help will be appreciated! Also, if the answer is going to be too technical to be written on a few lines, I'd appreciate for any good reference on lambda functions and how they work. One thing I have noticed, is that auto is not allowed when defining functions the usual way: void f(auto a) { } this does not compile.
Lambda is mostly equivalent to functor class: struct Lambda { template <typename T> auto operator()(T a) const std::cout << a << std::endl; return a; // make auto deduce as T } }; f(12) would instantiate Lambda::operator()<int> and f("test") would instantiate Lambda::operator()<const char*>.
72,686,433
72,703,068
ANSI escape code not working properly [C++]
I am using the ANSI escape code to print colored output. I am getting proper colored output in vs code integrated terminal. But when I am running the program in external command-prompt/Powershell, I am not getting the expected colored output. My program looks something like this: #define RESET "\033[0m" #define RED "\x1B[31m" #define GREEN "\x1B[32m" int main(int argc, char** argv){ if(argc != 1){ std::cout << RED ">> Invalid Arguments!" RESET; }else{ if(verify_password()){ ... ... ... }else{ std::cout << "\n>> " RED "Invalid Password!" RESET; } } return 0; } Complete Code NOTE: One weird thing I observed is that if I am entering the correct password then everything is working fine in both terminals(getting proper colors). But the problem is when either I am entering an incorrect password or an invalid amount of arguments What might be the reason for this? EDIT: I figured out a way to make it work. I find out that in order to make these escape codes work I need to have at least one call to system() function. But still, I am not sure how these things are connected.
Historically, consoles on Windows required use of the console API in the Windows SDK in order to do effects like color. But recent versions of Windows now support escape codes (and even UTF-8), but programs have to opt-in by calling SetConsoleMode with ENABLE_VIRTUAL_TERMINAL_PROCESSING. (Opting in preserves backward compatibility for older programs that aren't using escape codes or UTF-8.) If you're getting color in some places and not others, then I'd guess there's a problem related to the state the terminal/console is in when sending the escape codes. For example, if the terminal thinks it's already processing an escape code and a new one begins, it might not recognize either. I suppose this might also be a problem if one part of the program uses escape codes but another part uses the Console API.
72,686,690
72,686,871
std::filesystem example not compiling on c++ 17
I cant compile this official cpp filesystem reference example using c++ 17 clang: https://en.cppreference.com/w/cpp/filesystem/recursive_directory_iterator #include <fstream> #include <iostream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::current_path(fs::temp_directory_path()); fs::create_directories("sandbox/a/b"); std::ofstream("sandbox/file1.txt"); fs::create_symlink("a", "sandbox/syma"); // Iterate over the `std::filesystem::directory_entry` elements explicitly for (const fs::directory_entry& dir_entry : fs::recursive_directory_iterator("sandbox")) { std::cout << dir_entry << '\n'; } std::cout << "-----------------------------\n"; // Iterate over the `std::filesystem::directory_entry` elements using `auto` for (auto const& dir_entry : fs::recursive_directory_iterator("sandbox")) { std::cout << dir_entry << '\n'; } fs::remove_all("sandbox"); } The compiler is returning: /main.cpp:17:19: error: invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream') and 'const fs::directory_entry') std::cout << dir_entry << std::endl; Can anyone help?
There was a defect in C++17 standard that didn't allow operator<< to be called with std::filesystem::directory_entry, reported in LWG 3171. It's now fixed as defect report, but it seems clang only fixed it in version 14: https://godbolt.org/z/3arTcGYvY. gcc seems to have backported the fix to all versions that support std::filesystem (that is, gcc9.1 and up): https://godbolt.org/z/fh7cdMxso
72,687,106
72,691,230
Template for initialization of the "customer class" from Nicolai Josuttis' c++17 presentation
I just watched a presentation by Nicolai Josuttis “The Nightmare of Move Semantics for Trivial Classes” In the presentation he shows how to build a "perfect customer class", so that it's constructor accepts up to all three arguments with as few mallocs as possible. Here are the solutions he presents: // 11 mallocs (4cr + 7cp + 1mv) Customer(std::string f = "", std::string l = "", int i = 0) : first(f), last(l), id(i) {} // 5 mallocs (4cr + 1cp + 5mv) Customer(std::string f = "", std::string l = "", int i = 0) : first(std::move(f)), last(std::move(l)), id(i) {} // all manual combinations carefully avoiding ambiguities, such as // 5 mallocs (4cr + 1cp + 1mv) Customer(const std::string&, const std::string&, int i = 0); // 5 mallocs (4cr + 1cp + 1mv) template<typename S1, typename S2 = std::string, typename = std::enable_if<std::is_convertible_v<std::string>> Customer(S1&& f, S2&& l = "", int i = 0): first(std::forward<S1>(f)), last(std::forward<S1>(l)), id(i) {} In cases like this I use an idiom (shown below), that he didn't consider in the presentation, nor did I find it elsewhere, yet I think it is suitable in both terms of performance and usage. It uses private inheritance of a struct, that has the members. The constructor template uses a parameter pack to do the job. So I wonder: is there anything wrong with this approach? Should I expect some problems in performance or usage? Any other pitfalls? Is this a known idiom that I just missed? (But why it wasn't there?) Here is the code for the class: #include <string> #include <utility> struct CustomerData { std::string first; std::string last; int id; }; class Customer: private CustomerData { public: // Constructor template template<typename... Args> Customer(Args... args): CustomerData{std::move(args)...} { } }; Edit: 1) POD changed to struct (POD containing string is not a POD, thanks to a remark by Daniel Langr), 2) added an explanatory sentence if one doesn't want to watch the whole video Edit 2: std::forward changed to std::move, thanks to remark of Jarod42 Edit 3: added reference code on request of apple apple
template <typename Args> Customer(Args... args) : CustomerData{std::move(args)...} { } is comparable to Customer(std::string first, std::string last = "", int id = -1) : first(std::move(first)), last(std::move(last)), id(id) {} (Which is the preferred variant from the video, but not the most efficient, as there is some (up to 4) extra move constructor) Default values (which is also a concern in the video) can be handled directly in your data structure. Performance are the same. Your version is less verbose, but also less self documenting. As for most template (forwarding reference in particular), it disallows initializer_list (test case not used/shown in the video): Customer c({42, 'a'}, {it1, it2}, 51); Your version is not SFINAE friendly: std::is_constructible_v<Customer, float, std::vector<int>> would give incorrect answer. In the same way, example from video about inheritance: Vip vip{/*..*/}; Customer c(vip); // Would select wrongly you constructor You can add SFINAE/requires to handle those cases though. I would compare with another alternative template <typename... Args> requires(is_aggregate_constructible_v<CustomerData, Args&&...>) Customer(Args&&... args) : CustomerData{std::forward<Args>(args)...} { } which would be comparable to template <typename S1, typename S2 = std::string> requires (std::is_constructible_v<std::string, S1&&> && std::is_constructible_v<std::string, S2&&>) Customer(S1&& first, S2&& last = "", int id = -1) : first(std::forward<S1>(first)), second(std::forward<S2>(second)), id(id), {} The most efficient alternative. Again, Same performance less verbose and potentially less self documenting. Here, both versions are template, and both versions have the issue with the construction with the initializer list. To conclude, your version without requires has some pitfalls. If you add the requires, then going to the proposed alternative (forwarding reference instead of by value) would be more efficient.
72,687,290
72,687,379
c++ overloaded (stream extraction and insertion) operator function as member function?
From c++ how to program 10th edition by deitel //Fig. 10.3: PhoneNumber.h //PhoneNumber class definition #ifndef PHONENUMBER_H #define PHONENUMBER_H #include <iostream> #include <string> class PhoneNumber { friend std::ostream& operator<<(std::ostream&, const PhoneNumber&); friend std::istream& operator>>(std::istream&, PhoneNumber&); private: std::string areaCode; //3-digit area code std::string exchange; //3-digit exchange std::string line; //4-digit line }; #endif // PHONENUMBER_H //Fig. 10.4: PhoneNumber.cpp //Overloaded stream insertion and stream extraction operators #include <iomanip> #include "PhoneNumber.h" using namespace std; //overloaded stream insertion operator; cannot be a member function //if we would like to invoke it with cout << somePhoneNumber; ostream& operator<<(ostream& output, const PhoneNumber& number) { output << "Area code: " << number.areaCode << "\nExchange: " << number.exchange << "\nLine: " << number.line << "\n" << "(" << number.areaCode << ") " << number.exchange << "-" << number.line << "\n"; return output; //enables cout << a << b << c; } //overloaded stream extraction operator; cannot be a member function //if we would like to invoke it with cin >> somePhoneNumber; istream& operator>>(istream& input, PhoneNumber& number) { input.ignore(); //skip ( input >> setw(3) >> number.areaCode; //input area code input.ignore(2); //skip ) and space input >> setw(3) >> number.exchange; //input exchange input.ignore(); //skip dash (-) input >> setw(4) >> number.line; //input line return input; //enables cin >> a >> b >> c } //Fig. 10.5: fig10_5.cpp //Demonstrating Class PhoneNumber's overloaded stream insertion //and stream extraction operators. #include <iostream> #include "PhoneNumber.h" #include <string> using namespace std; int main() { PhoneNumber phone; //create object phone cout << "Enter phone number in the form (555) 555-5555:" << endl; //cin >> phone invokes operator>> by implicitly issuing //the non-member function call operator>>(cin, phone) cin >> phone; //cout << phone invokes operator<< bby implicitly issuing //the non-member function call operator<<(cout, phone) cout << phone << endl; } I understand from the book that the overloaded operator function for binary operator can be member function only when the left operand is an object of the class in which the function is a member because the member function can only be accessed by left operand which is the object of the class. however I don't understand this part " The overloaded stream insertion operator (<<) is used in an expression in which the left operand has type ostream&, as in cout << classObject. To use the operator in this manner where the right operand is an object of a user-defined class, it must be overloaded as a non-member function. To be a member function, operator << would have to be a member of class ostream. This is not possible for user-defined classes, since we are not allowed to modify C++ Standard Library classes. " my question is whether the stream extraction and insertion operator is part of the ostream and istream respectively? what does the part highlighted in bold mean? My guess is that we cannot add user defined function into the C++ Standard Library class but the part in bold makes me kind of confused. do we have to add the operator << as member of class ostream to make the overloaded operator function as member function of ostream? I always thought that stream << and >> operator were part of ostream and istream respectively. Correct me if I am wrong. thank you in advance.
No, not for regular user defined types. The functions you made into friends in your class definition are free functions: std::ostream& operator<<(std::ostream&, const PhoneNumber&); std::istream& operator>>(std::istream&, PhoneNumber&); std::basic_ostream does have some operator<< member overloads for fundamental types, such as int, and some types defined in the standard library though. If you inherit from some of those standard types, like std::basic_streambuf<CharT, Traits>, you will be able to use the basic_ostream::operator<< member overloads for those types. It means that you are not allowed to modify the definition of std::basic_ostream to add std::basic_ostream& operator<<(const PhoneNumber&) as a member function.
72,687,366
72,687,423
What's the relation between `std::cout` and `std::ostream`?
I saw the code snippet below somewhere. #include <iostream> int main() { std::ostream& os = std::cout; os << "thanks a lot" << std::endl; return 0; } Since the aforementioned code snippet works well, it indicates that std::cout is derived from std::ostream. But I can't find any direct reference yet. As per the document, which says that[emphasis mine]: The global objects std::cout and std::wcout control output to a stream buffer of implementation-defined type (derived from std::streambuf), associated with the standard C output stream stdout. The above quotation says that std::cout controls ouput to a type which derived from std::streambuf other than std::cout derived from std::streambuf. And I only find the declaration of std::cout in a file named /usr/include/c++/7/iostream: extern ostream cout; /// Linked to standard output I can't find the implementation of std::cout.
ostream is a class. cout is an instance of that class. This is no different from class Person {}; Person john;. Person is the class, john is an instance of that class. The C++ standard library just happens to create an instance (cout) of this particular class (ostream) ahead of time, configured to write to the standard output stream. The line std::ostream& os = std::cout; defines a new variable called os, which is of type ostream&, that is a reference to an ostream. It then makes it a reference to the already defined variable cout.
72,687,538
72,693,115
boost::regex_replace
Currently I have a problem with boost :: regex, I need to find the appropriate word և replace. with the corresponding word. My code now looks like this. std::string name = ptap; std::string name_regex = "\\b" + name + "\\b"; boost::regex reg(name_regex); checks_str = boost::regex_replace( checks_str, reg, alias_name ); There are words in the file that look like "ptap.power" because regex reads the dot as any character. The initial part of this word (ptap) changes, which I do not need. How to fix this?
You can prevent a match if there is a dot after a word: #include <boost/regex.hpp> #include <string> #include <iostream> int main() { std::string str = "ptap ptap.power"; std::string name = "ptap"; std::string rep = "pplug"; std::string regex_name = "\\b" + name + "\\b(?!\\.)"; boost::regex reg(regex_name); str = boost::regex_replace(str, reg, rep); std::cout << str << std::endl; return 0; } See the C++ demo. The (?!\.) is a negative lookahead that fails the match if there is a . char immediately to the right of the current location. To avoid matching the keyword if there is a dot before, add a negative lookbehind: std::string regex_name = "\\b(?<!\\.)" + name + "\\b(?!\\.)";
72,687,632
72,688,034
How to store command output and exitcode from terminal in a variable
From here I have the code that gives me the command line output and the exit code. Unfortunately I don't understand much of that operator overloading and if I try to rewrite it to the simple code I know (with global variables i.e.) I always get the wrong exit code status of 0. So how can I modify the following code so I can store the output and the exit code status for future use? #include <cstdio> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <array> struct CommandResult { std::string output; int exitstatus; friend std::ostream &operator<<(std::ostream &os, const CommandResult &result) { os << "command exitstatus: " << result.exitstatus << " output: " << result.output; return os; } bool operator==(const CommandResult &rhs) const { return output == rhs.output && exitstatus == rhs.exitstatus; } bool operator!=(const CommandResult &rhs) const { return !(rhs == *this); } }; class Command { public: /** * Execute system command and get STDOUT result. * Like system() but gives back exit status and stdout. * @param command system command to execute * @return CommandResult containing STDOUT (not stderr) output & exitstatus * of command. Empty if command failed (or has no output). If you want stderr, * use shell redirection (2&>1). */ static CommandResult exec(const std::string &command) { int exitcode = 255; std::array<char, 1048576> buffer {}; std::string result; #ifdef _WIN32 #define popen _popen #define pclose _pclose #define WEXITSTATUS #endif FILE *pipe = popen(command.c_str(), "r"); if (pipe == nullptr) { throw std::runtime_error("popen() failed!"); } try { std::size_t bytesread; while ((bytesread = fread(buffer.data(), sizeof(buffer.at(0)), sizeof(buffer), pipe)) != 0) { result += std::string(buffer.data(), bytesread); } } catch (...) { pclose(pipe); throw; } exitcode = WEXITSTATUS(pclose(pipe)); return CommandResult{result, exitcode}; } }; int main () { std::cout << Command::exec("echo blablub") << std::endl; } Here is my code, the global variable is correct in the function but is overwritten afterwards. #include <cstdio> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <array> int exitcode = 555; std::string exec(const std::string cmd) { int exitcode = 255; std::array<char, 128> buffer {}; std::string result; #ifdef _WIN32 #define popen _popen #define pclose _pclose #define WEXITSTATUS #endif FILE *pipe = popen(cmd.c_str(), "r"); if (pipe == nullptr) { throw std::runtime_error("popen() failed!"); } try { std::size_t bytesread; while ((bytesread = fread(buffer.data(), sizeof(buffer.at(0)), sizeof(buffer), pipe)) != 0) { result += std::string(buffer.data(), bytesread); } } catch (...) { pclose(pipe); throw; } exitcode = WEXITSTATUS(pclose(pipe)); std::cout<<exitcode<<'\n'; return result; } int main (){ exec("echo bla"); std::cout<<exitcode<<'\n'; }
Assuming the code provided in the article is correct and does what it should do, it is already doing all you need. The exit code and output are returned from the exec function. You only have to use the returned CommandResult and access its members: int main() { auto result = Command::exec("echo blablub"); std::cout << result.output << "\n": std::cout << result.exitstatus << "\n"; }
72,687,724
72,687,862
C#: Use negative char numbers in C imported dll
I imported a DLL that I compiled with rato.hpp: #ifndef RATO_H #define RATO_H extern "C" { __declspec(dllexport) void mouse_move(char button, char x, char y, char wheel); } #endif and rato.cpp: typedef struct { char button; char x; char y; char wheel; char unk1; } MOUSE_IO; void mouse_move(char button, char x, char y, char wheel) { MOUSE_IO io; io.unk1 = 0; io.button = button; io.x = x; io.y = y; io.wheel = wheel; if (!callmouse(&io)) { mouse_close(); mouse_open(); } } When importing it in my CSharp code, I can't cast negative values: [DllImport("Rato.dll")] public static extern void mouse_move(char button, char x, char y, char wheel); mouse_move((char)0,(char)0,(char)-150,0); I tried to convert, but it doesn't work, it keeps sending positive values instead of negative. EDIT: Tried to convert to sbyte but get error System.OverflowException: 'Value was either too large or too small for a signed byte.' [DllImport("Rato.dll")] public static extern void mouse_move(sbyte button, sbyte x, sbyte y, sbyte wheel); mouse_move(0,0,Convert.ToSByte(-150),0); How can I sucessfully pass negative char value to C imported DLL?
char in C# is a 16-bit unsigned type so obviously you can't use it to interop with char in C++. sbyte is the way to go. However the range of sbyte is -128 to 127, similar to unsigned char in C when CHAR_BIT == 8, so obviously -150 can't fit in C# sbyte/C char Note: char in C can be signed or unsigned, so if for example you use the /J option in MSVC or the -funsigned-char option in GCC in your project then you can't pass a negative value to the C function
72,687,761
72,690,616
a sleek C++ variadic named test output
I've made some variadic output macros, especially for test output purposes. Examples: C++-code // output: function file(first and last char) linenumber variable=value L(i,b); // result e.g. {evenRCpower@ih2943: i=36 b=1 @} L(hex,pd,dec,check.back(),even,"e.g."); // result e.g.: {way@ih3012: pd=babbbaba check.back()=15216868001 even=1 e.g. @} They are working fine, having some minor restrictions, which can be lowered by more text analysis (restricted usage of comma and output specifications). Up to now, they are working at least under g++1z and c++1z. My questions: Main question: How to get the macro completely thread safe? Is there a solution needing no textual analysis, e.g. to avoid #VA_ARGS and get the names for every parameter separated? How to distinguish parameters from output manipulators (necessary)? What's to change for other (newer) C++ and g++ versions? Even to write one complete line into one local string using a locally defined outstream isn't completely solving the problem of output mixing in parallel work - but why? In which C++ version this problem will be solved? I'll give a simplified base version with use of "std::out" will work fine, but of course give bad results, when used in parallel threads: #define WO_IS 1 #define L(...) locate(__FILE__,__LINE__,__func__,"\n{",": "," @}\n",#__VA_ARGS__,##__VA_ARGS__) string argTExcludes = " hex dec std::hex std::dec ", funcExcludes = " setprecision "; string argT(const string sarg,int &nextpos) { // NO exact analysis!! Simple strings and chars allowed, but parameters with commata like in f(x,y,"A,",','): crazy output !! int i = nextpos+1, pos = i, follow = 0; string nom; bool apo = false; for (; i < sarg.size(); i++) if(sarg.at(i) == ' ') { ; } else if ((sarg.at(i) == ',')||(i == (sarg.size()-1))) { nom = sarg.substr(pos,i-pos); if (argTExcludes.find(nom) != std::string::npos) { nextpos = i; return ""; }; break; } else { if ((sarg.at(i) != ' ') && (!follow++) && ((sarg.at(i) == '"')||(sarg.at(i) == '\'')) ) apo = true; if ((sarg.at(i) == '"') && ( (i==0)||((i > 0) && (sarg.at(i-1) != '\'')) )) { i++; while ((sarg.at(i) != '"') && (i < sarg.size())) i++; }; if (sarg.at(i) == '(') { nom = sarg.substr(pos,i-pos); if (funcExcludes.find(nom) != std::string::npos) apo = true; }; }; nextpos = i; return (apo)?"":sarg.substr(pos,i-pos)+"="; }; template <typename... Ts> inline void locate(string ort,long line,string funct,const string prefix, const string trenner, const string postfix, string sarg, Ts... args) { #if WO_IS > 0 // all range restrictions abandoned int pos = -1; bool apo; sarg += ","; std::ios_base::fmtflags f( cout.flags() ); std::cout << prefix << funct << '@' << ort[0] << ort.back() << dec << line << trenner; cout.flags( f ); ((std::cout << argT(sarg,pos) << args << ' '), ...); // forbidden: endl - it will give syntax error even when no blank at end // ((std::cout << argT(sarg,pos); std::cout << args; std::cout << ' '), ...); // forbidden: endl - it will also give syntax error if (postfix == "\0") std::cout.flush(); else std::cout << postfix; // << endl; #endif };
Is there a solution needing no textual analysis, e.g. to avoid #VA_ARGS and get the names for every parameter separated? You might do it with hard coded limit. Some utilities MACRO to "iterate" over __VA_ARGS__: #define COUNT_VA_ARGS(...) TAKE_10(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) #define TAKE_10(_1, _2, _3, _4, _5, _6, _7, _8, _9, N,...) N #define JOIN(a, b) JOIN_H(a, b) #define JOIN_H(a, b) a ## b #define WRAP_VA_ARGS_0(wrap) #define WRAP_VA_ARGS_1(wrap, x0) wrap(x0) #define WRAP_VA_ARGS_2(wrap, x0, x1) wrap(x0), wrap(x1) #define WRAP_VA_ARGS_3(wrap, x0, x1, x2) wrap(x0), wrap(x1), wrap(x2) #define WRAP_VA_ARGS_4(wrap, x0, x1, x2, x3) wrap(x0), wrap(x1), wrap(x2), wrap(x3) #define WRAP_VA_ARGS_5(wrap, x0, x1, x2, x3, x4) wrap(x0), wrap(x1), wrap(x2), wrap(x3), wrap(x4) // ... // Call into one of the concrete ones above #define WRAP_VA_ARGS(wrap, ...) JOIN(WRAP_VA_ARGS_, COUNT_VA_ARGS(__VA_ARGS__))(wrap, __VA_ARGS__) Then, you might do something like template <typename... Ts> void print(std::source_location loc, const Ts&...args) { std::cout << loc.function_name() << ":" << loc.line() << std::endl; ((std::cout << args << " "), ...) << std::endl; } #define NAMED_PAIR(x) #x, x #define PRINT(...) print(std::source_location::current(), WRAP_VA_ARGS(NAMED_PAIR, __VA_ARGS__)) Demo
72,687,797
72,697,141
Output from reading text file is repeated C++ file handling
I would like to read my text file and output it exactly like in the input but the thing is, they are repeated! and the number will be either 1 or 0 My c++ code #include <iostream> #include <fstream> #include <string> using namespace std; int n, count, size = 10; string name, ID, stamina, plusmode, type; int main () { ifstream data; data.open("cards2.txt"); while (data) { data >> n; getline (data, name, '\t'); getline (data, ID, '\t'); getline (data, stamina, '\t'); getline (data, plusmode, '\t'); getline (data, type, '\t'); for (count = 1; count <= 10; count++) { cout << n << " " << name << " " << ID << " " << stamina << " " << plusmode << " " << type << endl; } } } My txt file 1 Abyss Devolos F0647 Balance NA SpeedStorm 2 Ace Dragon E7609 Attack NA HyperSphere 3 Anubion A2 E1057 Defense NA Dual-Layer 4 Balar B4 E4726 Attack NA SlingShock 5 Crystal Dranzer F0217 Balance NA Burst 6 Cyclone Belfyre F3965 Stamina Attack QuadDrive 7 Dark-X Nepstrius E4749 Defense NA SlingShock 8 Diomedes D2 E1062 Attack NA Dual-Layer 9 Doomscizor E1033 Attack NA SwitchStrike 10 Vatryek Wing Accel B9492 Attack NA Burst My output in terminal 1 Abyss Devolos F0647 Balance 1 Abyss Devolos F0647 Balance 1 Abyss Devolos F0647 Balance 1 Abyss Devolos F0647 Balance 1 Abyss Devolos F0647 Balance 1 Abyss Devolos F0647 Balance 1 Abyss Devolos F0647 Balance 1 Abyss Devolos F0647 Balance 1 Abyss Devolos F0647 Balance 1 Abyss Devolos F0647 Balance 0 Abyss Devolos F0647 Balance 0 Abyss Devolos F0647 Balance 0 Abyss Devolos F0647 Balance 0 Abyss Devolos F0647 Balance 0 Abyss Devolos F0647 Balance 0 Abyss Devolos F0647 Balance 0 Abyss Devolos F0647 Balance 0 Abyss Devolos F0647 Balance 0 Abyss Devolos F0647 Balance 0 Abyss Devolos F0647 Balance Please help me. I dont know how to make it not repeated
Here's some code that reads and prints your data file. I am assuming that your data is tab delimited, which is what your initial code implies, but you haven't explicitly stated anywhere. int main() { ... int n; string name, ID, stamina, plusmode, type; while (data >> n) // continue reading until no more numbers { data.ignore(); // skip the tab immediately after the number getline(data, name, '\t'); getline(data, ID, '\t'); getline(data, stamina, '\t'); getline(data, plusmode, '\t'); getline(data, type, '\n'); // last data item is terminated by \n cout << n << " " << name << " " << ID << " " << stamina << " " << plusmode << " " << type << endl; } } Your original code made two mistakes (which I've indicated with comments). The first error was that after reading the number in the first column, you failed to realise that the next character is a tab. You want to ignore that tab, so that you can start reading the next column. That's what data.ignore() does, it ignores the next character in the input. The second error is that your code didn't reflect that the type column is not terminated by a tab but by a newline, so getline(data, type, '\t'); is wrong, it should be getline(data, type, '\n'); Both these errors are examples of where you haven't thought carefully enough about what the input is, and what the code you have written does. You need to be precise in your thinking.
72,687,892
72,688,160
Question about the implementation of std::istream& operator>>(std::istream& is, icmp_header& header)
I saw such an implementation for asio::icmp_header in asio-1.22.1/src/examples/cpp03/icmp/icmp_header.hpp class icmp_header { //omit several functions friend std::istream& operator>>(std::istream& is, icmp_header& header) { return is.read(reinterpret_cast<char*>(header.rep_), 8); } //omit several functions private: unsigned char rep_[8]; //no other member variable, indeed } Why not write the method like this: friend std::istream& operator>>(std::istream& is, icmp_header& header) { return is.read(reinterpret_cast<char*>(header.rep_), sizeof(icmp_header)); } You see class icmp_header is a simple class without any inheritance. To avoid the unforeseen\uncertain padding on different operating systems?
It is not the class definition in the header file that defines how large an ICMP header is, but it is the protocol definition. And from there it can be derived that the header is 8 octets (bytes). Therefore, it is reasonable to hard-code the size in the read() function call in order to ensure that exactly that many bytes are read. That the size of the buffer in the class definition is also 8 characters, is just because to make it sufficiently large. Theoretically, the implementers could have chosen a larger size for the buffer, but that would not change the fact that the data stream has just 8 bytes dedicated for the header.
72,688,090
72,688,312
What is the C++2014 equivalent of the C++2017 concept std::invoke_result_t?
In my current project (Hardware Acceleration with Xilinx Vitis) I'm trying to include a header only Library which uses several C++2017 features. Xilinx Vitis however does not allow C++2017 to be used. Now since it is a header only library I tried to just create a local copy of it and replace all C++ 2017 Features with their C++ 2014 Equivalents. There are however 4 Lines in the Code which look like this: using X = typename std::invoke_result_t<Fin, size_t>::first_type; using Y = typename std::invoke_result_t<Fin, size_t>::second_type; Now, the way I understood the documentation found on Cppreference I figured that the correct way to rewrite these lines would look like this: using X = typename std::result_of_t<Fin>::first_type; using Y = typename std::result_of_t<Fin>::second_type; However, this causes several (same) errors while compiling: /Workspace/PGM-index/include/pgm/piecewise_linear_model.hpp:333:49: error: invalid use of incomplete type ‘class std::result_of<pgm::PGMIndex<K, Epsilon, EpsilonRecursive, Floating>::build(RandomIt, RandomIt, size_t, size_t, std::vector<pgm::PGMIndex<K, Epsilon, EpsilonRecursive, Floating>::Segment>&, std::vector<long unsigned int, std::allocator >&) [with RandomIt = __gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator > >; K = int; long unsigned int Epsilon = 128; long unsigned int EpsilonRecursive = 4; Floating = float; size_t = long unsigned int]::<lambda(auto:8)> >’ So if anyone could help me understand how I would have to rephrase those lines to get the compilation to complete, I would be thankful. If there is any Information missing, please let me know.
The single parameter to std::result_of_t is a (very misleading1) function type. In your case it would be std::result_of_t<Fin(size_t)>. That function type denotes a function that takes the arguments and returns the callable type that you are inspecting. For this reason it was deprecated in C++17 and removed in C++20.
72,688,295
72,689,425
Converting qsort function to std::sort
I currently have this comparator function that sorts a custom struct using qsort, and I want to port it to std::sort, but it seems like it needs to return a bool value instead of -1, 0 and 1, how would I rewrite it? int tsort = 1, sorta = 1; static auto titleSort(const void *c1, const void *c2) -> int { switch (tsort) { case 0: return ((Title *) c1)->listID - ((Title *) c2)->listID; case 1: return strcmp(((Title *) c1)->shortName, ((Title *) c2)->shortName) * sorta; case 2: if (((Title *) c1)->isTitleOnUSB == ((Title *) c2)->isTitleOnUSB) return 0; if (((Title *) c1)->isTitleOnUSB) return -1 * sorta; if (((Title *) c2)->isTitleOnUSB) return 1 * sorta; return 0; case 3: if (((Title *) c1)->isTitleOnUSB && !((Title *) c2)->isTitleOnUSB) return -1 * sorta; if (!((Title *) c1)->isTitleOnUSB && ((Title *) c2)->isTitleOnUSB) return 1 * sorta; return strcmp(((Title *) c1)->shortName, ((Title *) c2)->shortName) * sorta; default: return 0; } }
If possible, get rid of int tsort = 1, sorta = 1; and use directly the appropriate method. The dispatch, if needed, can be done with something like (C++20): void sortTitle(std::vector<Title>& title, int tsort = 1, sorta = 1) { switch (tsort) { case 0: std::ranges::sort(titles, std::ranges::less{}, &Title::listID); break; case 1: { const auto proj = [](const Title& title){ return std::string_view(title.shortName); }; if (sorta == 1) { std::ranges::sort(titles, std::ranges::less{}, proj); } else { std::ranges::sort(titles, std::ranges::greater{}, proj); } break; } case 2: if (sorta == 1) { std::ranges::sort(titles, std::ranges::less{}, &Title::isTitleOnUSB); } else { std::ranges::sort(titles, std::ranges::greater{}, &Title::isTitleOnUSB); } break; case 3: { const auto proj = [](const Title& title){ return std::make_tuple(title.isTitleOnUSB, std::string_view(title.shortName)); }; if (sorta == 1) { std::ranges::sort(titles, std::ranges::less{}, proj); } else { std::ranges::sort(titles, std::ranges::greater{}, proj); } break; } } }
72,689,409
72,689,495
C++ Why can't I throw an abstract class?
I have a pure virtual class, BaseClass, with no data members and a protected constructor. It exists only to provide the interface for a subclass (which is templated). I want just about all the functionality implemented in the base class. Functions that operate on these typically would return BaseClass&, to allow convenient chaining of operations. All well and good until I try to throw an instance, returned by reference from one of the functions. In short, I am throwing a reference to an abstract class, but I'm secure in the knowledge that it's guaranteed to be a fully constructed child class instance with all virtual functions intact. That's why the BaseClass constructor is protected. I'm compiling against a C++14 compiler. It's refusing to allow me to throw an abstract class. One of the main points of the class is that I can construct a subclass, immediately call functions on it to add information, and then throw it, all in one fell swoop: throw String<72>().addInt(__LINE__).addText("mom says no"); //does not compile but addText(), very reasonably, returns BaseClass&, and the compiler refuses. How do I? Moving all the member functions into the subclass seems obscene. I can hack around it by static casting the whole expression before the throw: throw static_cast<String<72&>( //works, ugly BaseClassString<72>().addText(where).addText(why).addText(resolution)); and even create a macro to hide the ugly mechanics and ensure some safety, but am I missing something? This seems like case of C++ preventing a perfectly workable technique.
Why can't I throw an abstract class? Due to [except.throw] /3 Throwing an exception copy-initializes ([dcl.init], [class.copy.ctor]) a temporary object, called the exception object. /5 When the thrown object is a class object, the constructor selected for the copy-initialization as well as the constructor selected for a copy-initialization considering the thrown object as an lvalue shall be non-deleted and accessible, even if the copy/move operation is elided ([class.copy.elision]).
72,689,494
72,689,599
std::map object destructor getting called?
I have a global map object which contains an ID and a class object, but I don't understand why the destructor for the objects in the map are getting called. #include <map> #include <iostream> #include <cassert> #include <chrono> #include <thread> class TestMapObject{ private: std::string m_sName; public: TestMapObject(const std::string& sName){ std::cout << "Constructor called" << std::endl; m_sName = sName; } ~TestMapObject(){ std::cout << "Destructor called" << std::endl; } const std::string& GetName(){ return m_sName; } }; namespace Test{ enum ETestMapKeyId{ k_ETestMapKeyNone = 0, k_ETestMapKeyFirst, k_ETestMapKeySecond, }; std::map<ETestMapKeyId, TestMapObject> g_tMap; TestMapObject* GetMapObjectById(ETestMapKeyId eID){ auto itFound = g_tMap.find(eID); assert(itFound != g_tMap.end()); return &itFound->second; } } int main(){ Test::g_tMap.insert(std::pair<Test::ETestMapKeyId,TestMapObject>(Test::k_ETestMapKeyFirst,TestMapObject("Alice"))); Test::g_tMap.insert(std::pair<Test::ETestMapKeyId,TestMapObject>(Test::k_ETestMapKeySecond,TestMapObject("Mocha"))); //destructor gets called here std::cout << " are we destructed? " << std::endl; TestMapObject* tmKeyFirst = Test::GetMapObjectById(Test::k_ETestMapKeyFirst); TestMapObject* tmKeySecond = Test::GetMapObjectById(Test::k_ETestMapKeySecond); for(;;){ std::this_thread::sleep_for (std::chrono::seconds(1)); std::cout << tmKeyFirst->GetName() << std::endl ; std::cout << tmKeySecond->GetName() << std::endl ; } return 0; } I'm able to retrieve a pointer to the objects with GetMapObjectById and continuously able to print their name (Which might be undefined behavior considering their destructor was called). But I'm unsure why the destructor gets called before the application ends.. Output Constructor called Destructor called Destructor called Constructor called Destructor called Destructor called are we destructed? ---continues loop print Alice Mocha
What you see is not the std::map getting destroyed, but the temporaries you are using to insert elements in the map. You can use emplace to avoid the construction (and destruction) of that temporaries: Test::g_tMap.emplace(Test::k_ETestMapKeyFirst,"Alice"); Test::g_tMap.emplace(Test::k_ETestMapKeySecond,"Mocha"); Live Demo
72,689,542
72,689,866
Should static_pointer_cast calls be std:: qualified, or relied upon ADL?
static_pointer_cast resides in std namespace. Yet it takes pointers that are also in std namespace. So both std:: qualified calls and unqualified calls are accepted. Which one is the right, more idiomatic way to call static_pointer_cast?
Generally, if you know exactly which function you want to call, rather than allowing for customization, I would try to avoid ADL, implying avoiding unqualified calls. In this case it is not expected for a library to provide its own static_pointer_cast for shared_ptrs of their own type. You always want to call the std version. Calling std::static_pointer_cast directly guarantees that no other such static_pointer_cast will interfere. If you include e.g. a library that also declared some function named static_pointer_cast which happens to be viable for your call and is a better fit or more specialized in overload resolution than the std one, you may accidentally call it instead if you use an unqualified call. I think this is extremely unlikely to be a problem in the case of static_pointer_cast, because it is unlikely that a library will use that name in a way that the overload will be viable for a normal std::static_pointer_cast call and be at the same time a better match, all of it without realizing the implications. But for example for std::launder this seems to have happened in some code bases (the other way around) when C++17 was introduced and the std overload turned out to be a better match than the library one in an unqualified call with a standard library type as argument. If you look at for example C++ standard library implementations you will see that they follow this rule to avoid unqualified calls very strictly and use them only where the standard expects the user to be able to customize the call. Of course for non-library code especially this might not be as important of a consideration. But also note that prior to C++20, if there is no function template named static_pointer_cast found by usual unqualified lookup, then an unqualified call using an explicit template argument list (which are required for static_pointer_cast) will fail anyway. So before C++20 you don't really have the choice to use the unqualified call without a prior using declaration to import the function.
72,690,058
72,690,251
Raylib my Screen Collisions are not accurate
So I'm new to raylib and, basically, I'm trying to make a sandbox game and I am trying to make it so that when the player places a square or material when that material hits the edge of the screen it stops. Currently, my square when it falls it goes to the edge of the screen and it stops. but there's noticeable space between the screen, and the squares flicker and the squares don't stop on the same X level. This Code is called when the user clicks on the screen. This DrawMat function is called when the user clicks and from there the square falls to the bottom of the screen. Heres My Code struct Mat { float X, Y; float SpeedX, SpeedY; float Force; float Gravity; Vector2 MousePos; Vector2 size; Color color; void DrawMat() { DrawRectangle(MousePos.x, MousePos.y, size.x, size.y, color); MousePos.y += 9.81f; if (MousePos.x < 0 || MousePos.x > GetScreenWidth()) { MousePos.x *= -1; } if (MousePos.y < 0 || MousePos.y > GetScreenHeight()) { MousePos.y *= -1; } } }; int main() { InitWindow(800, 600, "Speed Z Presends to you... Satisfiying, Amazing, Niffty, Dreamy. SIMULATOR"); SetWindowState(FLAG_VSYNC_HINT); Mat Sand; Sand.MousePos = { -100, -100 }; Sand.size = { 5, 5 }; Sand.color = YELLOW; Sand.X = Sand.MousePos.x; Sand.Y = Sand.MousePos.y; Sand.SpeedX = 300; Sand.SpeedY = 500; Vector2 Mousepos = {-100, -100}; bool Mouseclicked = false; Vector2 RectSize = { 2, 2 }; int Numof = 0; std::vector<Mat> positions = {}; while (!WindowShouldClose()) { BeginDrawing(); ClearBackground(BLACK); for (size_t i = 0; i < positions.size(); i++) { positions[i].DrawMat(); } if (IsKeyPressed(KEY_ONE)) { Numof = 1; } if (Numof == 1) { if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) { Mouseclicked = true; Mousepos = GetMousePosition(); Sand.MousePos = GetMousePosition(); positions.push_back(Sand); } } Here is an image of What I mean:
I don't really understand how this code would work at all. But if what you mean is that the Y coordinate should be as close as possible to the edge, your if statement should be like so: if (MousePos.y < 0) { MousePos.y *= -1; } else if (MousePos.y > GetScreenHeight()) { MousePos.y = GetScreenHeight(); } Adjust the last expression as required. Maybe you need to subtract the height of the object so it doesn't disappear: else if (MousePos.y > GetScreenHeight() - size.y) { MousePos.y = GetScreenHeight() - size.y; } Why is that necessary? I would imagine that the rendering you make uses MousePos.x as the left position and MousePos.y as the top position like so: /---- this corner is (MousePos.x, MousePos.y) | | v | | +----------------+---- | | | | ^ |<- screen bottom edge | | | | size.y | +-------------|----------------|--|--------------+ | | v +----------------+---- So to keep the sand grain on screen, you must make sure that the corner is at a location that makes it visible. As we see on the ASCII picture, for Y it means the maximum is GetScreenHeight() - size.y. Note that you certainly have the same issue with the X coordinate (i.e. you may want the maximum to be GetScreenWidth() - size.x).
72,690,254
72,691,461
Spaceship operator on arrays
The following code is intended to implement comparison on an object that contains an array. Two objects should compare as <,==,> if all array elements compare like that. The following does not compile for a variety of reason: #include <compare> class witharray { private: array<int,4> the_array; public: witharray( array<int,4> v ) : the_array(v) {}; int size() { return the_array.size(); }; auto operator<=>( const witharray& other ) const { array< std::strong_ordering,4 > cmps; for (int id=0; id<4; id++) cmps[id] = the_array[id]<=>other.the_array[id]; return accumulate (cmps.begin(),cmps.end(), std::equal, [] (auto x,auto y) -> std::strong_ordering { return x and y; } ); }; }; First of all, the array of comparisons: call to implicitly-deleted default constructor of 'array<std::strong_ordering, 4> Then the attempt to accumulate the comparisons: no matching function for call to 'accumulate' Compiler explorer: https://godbolt.org/z/E3ovh5qGa Or am I completely on the wrong track?
Two objects should compare as <,==,> if all array elements compare like that. This is a fairly interesting order. One thing to note here is that it's a partial order. That is, given {1, 2} vs {2, 1}, those elements aren't all < or == or >. So you're left with unordered. C++20's comparisons do have a way to represent that: you have to return a std::partial_ordering. The way that we can achieve this ordering is that we first compare the first elements, and then we ensure that all the other elements compare the same. If any pair of elements doesn't compare the same, then we know we're unordered: auto operator<=>( const witharray& other ) const -> std::partial_ordering { std::strong_ordering c = the_array[0] <=> other.the_array[0]; for (int i = 1; i < 4; ++i) { if ((the_array[i] <=> other.the_array[i]) != c) { return std::partial_ordering::unordered; } } return c; } This has the benefit of not having to compare every pair of elements, since we might already know the answer by the time we get to the 2nd element (e.g. {1, 2, x, x} vs {1, 3, x, x} is already unordered, doesn't matter what the other elements are). This seems like what you were trying to accomplish with your accumulate, except accumulate is the wrong algorithm here since we want to stop early. You'd want all_of in this case: auto comparisons = views::iota(0, 4) | views::transform([&](int i){ return the_array[i] <=> other.the_array[i]; }); bool all_match = ranges::all_of(comparisons | drop(1), [&](std::strong_ordering c){ return c == comparisons[0]; }); return all_match ? comparisons[0] : std::partial_ordering::unordered; Which is admittedly awkward. In C++23, we can do the comparisons part more directly: auto comparisons = views::zip_transform( compare_three_way{}, the_array, other.the_array); And then it would read better if you had a predicate like: bool all_match = ranges::all_of(comparisons | drop(1), equals(comparisons[0])); or wrote your own algorithm for this specific use-case (which is a pretty easy algorithm to write): return all_same_value(comparisons) ? comparisons[0] : std::partial_ordering::unordered;
72,690,333
72,690,512
C++ std::max acting like std::min
When I try using the built-in max for (2, 8), and I get 2 for some reason. I also created my own functions like this: #define min(number_1, number_2) (number_1 < number_2 ? number_1 : number_2) #define max(number_1, number_2) (number_1 < number_2 ? number_2 : number_1) but it still fails. Here is the code: #include <iostream> #include <string> using namespace std; #define min(number_1, number_2) (number_1 < number_2 ? number_1 : number_2) #define max(number_1, number_2) (number_1 < number_2 ? number_2 : number_1) int main() { int start_position, end_position; int teleportation_start_position, teleportation_end_position; cin >> start_position >> end_position >> teleportation_start_position >> teleportation_end_position; cout << start_position << " " << end_position << " " << teleportation_start_position << " " << teleportation_end_position << "\n"; start_position = min(start_position, end_position); end_position = max(start_position, end_position); teleportation_start_position = min(teleportation_start_position, teleportation_end_position); teleportation_end_position = max(teleportation_start_position, teleportation_end_position); cout << start_position << " " << end_position << " " << teleportation_start_position << " " << teleportation_end_position << "\n"; } And I get with the input of 3 10 8 2 I get 3 10 8 2 3 10 2 2 Why is it 2 2? It still doesn't work when I delete the things I defined (#define). I only inserted a code snippet.
The error is that you are re-using the teleportation_start_position variable. teleportation_start_position = min(teleportation_start_position, teleportation_end_position); Before this line the state of your program is: teleportation_start_position = 8 teleportation_end_position = 2 But after, it is: teleportation_start_position = 2 teleportation_end_position = 2 So in the next line you are doing: teleportation_end_position = max(teleportation_start_position, teleportation_end_position); // teleportation_end_position = max(2, 2);
72,690,937
72,690,991
why here 2 cannot implicitly convert to MyClass object?
class MyClass { public: MyClass(int){} }; MyClass operator +(MyClass& lOperand, MyClass& rOperand) { return lOperand; } int main() { MyClass obj1(0); obj1 = obj1 + 2; // 1 } Here compiler says no match function of operator + in line 1. But I think 2 can be converted to a MyClass object as the constructor of MyClass is not explicit. If I take & away from the parameter, then it is OK.
I think 2 can be converted to a MyClass object as the constructor of MyClass is not explicit. The problem is that after the conversion from int to MyClass we will have a prvalue of type MyClass which cannot be bound to an lvalue reference to non-const MyClass. Basically, an lvalue reference to nonconst type cannot be bound to an rvalue. But an lvalue reference to a const type can be bound to an rvalue. For example, int &ref = 4; //not valid const int &r = 4; //valid To solve this, you can add a low-level const to the parameters as shown below: //----------------------------------------- vvvvv----------------------->low level const added MyClass operator +(const MyClass& lOperand, const MyClass& rOperand) { return lOperand; } Working demo
72,692,099
72,692,233
How can I pass a class member's fixed size array by reference?
I have a class Node that contains a fixed-size array. I have another class that creates an instance myNode and calls a function to assign 5 values to the fields in the array. I want to pass the array by reference so the function modifies the actual array and not a copy, but I can't figure out how. Node: class Node { public: // Constructor, destructor, other members, etc uint8_t mArray[5]; } Worker: class worker { void doStuff(uint8_t (&arr)[5]) { arr[0] = 12; arr[1] = 34; arr[2] = 56; arr[3] = 78; arr[4] = 90; } int main() { Node *myNode = new Node(); doStuff(myNode->mArray); // myNode->mArray is not modified } }
Yes, the array is modified. A minimal reproducible example: #include <cstdint> #include <iostream> class Node { public: uint8_t mArray[5]; }; class worker { void doStuff(uint8_t (&arr)[5]) { arr[0] = 12; arr[1] = 34; arr[2] = 56; arr[3] = 78; arr[4] = 90; } public: int main() { Node *myNode = new Node(); doStuff(myNode->mArray); for(auto v : myNode->mArray) { std::cout << static_cast<unsigned>(v) << ' '; std::cout << '\n'; } delete myNode; return 0; } }; int main() { worker w; return w.main(); } This prints the expected: 12 34 56 78 90 It'd be easier if you took a Node& in the function though: #include <cstdint> #include <iostream> class Node { public: uint8_t mArray[5]; }; class worker { void doStuff(Node& n) { n.mArray[0] = 12; n.mArray[1] = 34; n.mArray[2] = 56; n.mArray[3] = 78; n.mArray[4] = 90; // or just: // n = Node{12,34,56,78,90}; } public: int main() { Node *myNode = new Node(); doStuff(*myNode); // ... delete myNode; return 0; } }; int main() { worker w; return w.main(); }
72,692,330
72,692,377
C++ Getting points between 2 points
So I have 2 points where I want to get points in between them for smoother teleport travel. POINT a; //Character Position POINT b; //Some random map position I was using this formula to get a middle point first, but I want to add more points of travel before reaching POINT b. POINT midpoint(const POINT& a, const POINT& b) { POINT ret; ret.x = (a.x + b.x) / 2; ret.y = (a.y + b.y) / 2; return ret; } I thought I could just calculate middle points more frequently to get shorter positions but I was wondering if there was a more dynamic way of doing this instead of coding in several different middle points. I don't want to keep doing this simple approach: POINT middlepoint = midpoint(a, b); POINT closerpoint = midpoint(a, middlepoint); How I want it to travel - number of points don't matter too much
It's all just using proportions. void MakePoints( const POINT& a, const POINT& b, int n, std::vector<POINT> & pts ) { pts.clear(); pts.push_back( a ); int dx = b.x - a.x; int dy = b.y - a.y; for( int i = 1; i <= n, i++ ) { pts.emplace_back( a.x + dx * i / n, a.y + dy * i / n ); } }
72,692,700
72,692,780
What is the actual mechanism behind the constructor initializer list?
There are cases where we must use an initializer list in order to initialize members, like when we have const data members. So, what makes an initializer list able to initialize members while the constructor itself can't?
An initializer list always initializes all members. Full stop. Any members you fail to list have their default constructor called. If you reassign to them in the constructor body, then (in principle) you've just allocated and then immediately discarded one extra object. In the particular case of const, a const variable cannot be reassigned to. It's never correct to set an initialized const variable equal to another value. It can only be initialized the first time, never reassigned. struct Foo { const int x; int y; int z; Foo() : x(0), y(0) { // At this point, all three variables (even z) have been initialized. y = 0; // Okay, reassignment is fine but wasteful z = 0; // Same as above x = 0; // Error! Can't reassign to a const } }
72,692,926
72,694,131
Error using Eigen: invalid use of incomplete type ‘const class Eigen
I have the following code that works: Matrix <float, ny+1, nx> eXX; eXX.setZero(); Eigen::Matrix< double, (ny+1), (ny)> u; u.setZero(); for(int i = 0; i< nx; i++){ for(int j = 0; j< ny+1; j++){ eXX(j + (ny+1)*i) = (i)*2*EIGEN_PI/nx; u(j + (ny+1)*i) = cos(eXX(j + (ny+1)*i)); } } But when I write the following it doesn't work: Matrix <float, ny+1, nx> eXX; eXX.setZero(); Eigen::Matrix< double, (ny+1), (ny)> u; u.setZero(); for(int i = 0; i< nx; i++){ for(int j = 0; j< ny+1; j++){ eXX(j + (ny+1)*i) = (i)*2*EIGEN_PI/nx; } } u = eXX.matrix().cos();// -or- std::cos(eXX.array()); std::cout << u << "\n"; //error The full error message: Test.cpp:418:23: error: invalid use of incomplete type ‘const class Eigen::MatrixFunctionReturnValue<Eigen::Matrix<float, 11, 10> >’ 418 | u = eXX.matrix().cos(); | ^ In file included from /mnt/c/Users/eigen-3.4.0/eigen-3.4.0/Eigen/Core:163, from /mnt/c/Users/eigen-3.4.0/eigen-3.4.0/Eigen/Dense:1, from Test.cpp:21: /mnt/c/Users/eigen-3.4.0/eigen-3.4.0/Eigen/src/Core/util/ForwardDeclarations.h:305:34: note: declaration of ‘class Eigen::MatrixFunctionReturnValue<Eigen::Matrix<float, 11, 10> >’ 305 | template<typename Derived> class MatrixFunctionReturnValue; I guess I could try rewriting eXX without the use of for loop and pass it but that also doesn't work. Also, I read someone recommending adding something like #include <MatrixFunctionReturnValue> which made things a lot worse actually. Thanks. I am adding my includes as well here: #define _USE_MATH_DEFINES #include <cmath> #include<math.h> #include<stdio.h> #include "fftw3.h" #include <cstring> #include <sstream> #include <string> #include <sys/resource.h> #include <iostream> #include <vector> #include <fstream> #include <iomanip> #include <numeric> #include <assert.h> #include <Eigen/Dense> #include <unsupported/Eigen/FFT> #include <Eigen/SparseCore> #include <Eigen/Sparse>
The Matrix class is built for linear algebra. When you want to operate over the elements of a matrix you need to the use the Array class instead. See Eigen documentation on Array. The other way to do this is to use the unaryExpr to take each element of the matrix as an input. Here are both methods: #include <iostream> #include <Eigen/Dense> .... Eigen::Matrix<double, 3, 3> vals; vals.setZero(); std::cout << vals << '\n'; std::cout << "******\n"; std::cout << vals.array().cos() << '\n'; std::cout << vals << '\n'; std::cout << "******\n"; Eigen::Matrix<double, 3, 3> res = vals.unaryExpr([](double a) { return cos(a); }); std::cout << res << '\n'; std::cout << vals << '\n'; Take note of how vals changes (and doesn't change) with the various operations.
72,693,813
72,693,949
Simplest way to process HTTP post data in C++
I would like a website to send data to be stored to a database. Consequently I think I require a web server, listening to HTTP, parsing the POST, extracting the data and storing to database? I'd like the web server to be C++. However, I am struggling to find a simple example. I assume this is simple because we're just listening to a TCP socket and once all the data has been received, it's just a string parsing exercise? All the examples I can find seem way-over complicated. For example: https://www.boost.org/doc/libs/1_72_0/libs/beast/example/http/server/async/http_server_async.cpp Surely it shouldn't require 300-400 lines just to listen to a socket and parse a string? Is my understanding wrong/is there a simple way to process a HTTP POST in C++?
Writing your own web server in C++ that only supports a single HTTP connection from a single client at a time, assumes that the incoming HTTP requests are never malformed and always in a certain format, and always of a certain type, in the case of something unexpected happening, is not required to provide a proper HTTP response, would not be too hard. However, if you want your web server to be fully HTTP/1, HTTP/2 or HTTP/3 compliant, then writing such a server would be a lot of work, as those standards are dozens or even hundreds of pages long. It would probably be more meaningful to use existing HTTP server software, such as Apache HTTP Server, and write your own programs that are designed to serve individual HTTP requests, and to configure the server to call these programs for certain URLs. That way, you won't have to deal with most of the details of HTTP, but you will still have to deal with HTTP requests and HTTP responses. Some scripting languages such as PHP (which is designed to run on a web server) handle most of the remaining HTTP details for you, so you for example don't have to worry much about interpreting the HTTP request header and creating a HTTP response header. These scripting languages generally also allow you to connect to an external database server. If you don't want to use a scripting language, but would prefer for the individual HTTP requests to be handled by programs written in C++, then this is possible too, for example using CGI or an API provided by the HTTP server software.
72,694,301
72,694,436
In cppreference's description of std::basic_ostream, what does "constructing and checking the sentry object" mean?
The documentation for std::basic_ostream<CharT,Traits>::write says [emphasis mine]: Behaves as an UnformattedOutputFunction. After constructing and checking the sentry object, outputs the characters from successive locations in the character array whose first element is pointed to by s. Characters are inserted into the output sequence until one of the following occurs: exactly count characters are inserted inserting into the output sequence fails (in which case setstate(badbit) is called) How am I to understand the statement in bold? What's this so-called "sentry object"? As far as I can see, when std::basic_ostream<CharT,Traits> is called there must already exist an instance whose type is std::basic_ostream. For example: #include<iostream> int main { std::string str{"thanks for your attention to this matter"}; std::cout.write(str.data(), str.length()); } Notes: std::cout's type is std::ostream and std::ostream is defined as typedef std::ostream std::basic_ostream<char>.
If you follow the UnformattedOutputFunction link in the text you quoted, you will find the following description of what the sentry is and what it does: A UnformattedOutputFunction is a stream output function that performs the following: Constructs an object of type basic_ostream::sentry with automatic storage duration, which performs the following if eofbit or badbit are set on the output stream, sets the failbit as well, and if exceptions on failbit are enabled in this output stream's exception mask, throws ios_base::failure. flushes the tie()'d output stream, if applicable. Checks the status of the sentry by calling sentry::operator bool(), which is equivalent to basic_ios::good. If the sentry returned false or sentry's constructor threw an exception, no output takes place If the sentry returned true, attempts to perform the desired output by inserting the characters into the output stream as if by calling rdbuf()->sputc() or rdbuf()->xsputn(). Additionally, rdbuf()->overflow() and rdbuf()->sync() may be called, but no other virtual member function of std::basic_streambuf. if an exception is thrown during output, sets badbit in the output stream. If exceptions on badbit are enabled in this stream's exception mask, the exception is also rethrown. If no exception was thrown, returns the value specified by the function. In any event, whether terminating by exception or returning, the sentry's destructor is called before leaving this function. Also, the documentation for FormattedOutputFunction (ie operator<<) has a similar description for its use of the sentry. So, basically, every output method of ostream constructs an instance of the nested ostream::sentry class before performing the output work. The sentry makes sure that the ostream is in a valid state to accept output data. If it is not, the ostream is put into a failure state, and an exception is thrown if needed.
72,695,066
72,695,142
How to insert multiple fixed objects of a class inside another class c++
class Distance{ private: float km; //some member functions like //rounding off } class Payment{ private: std::unordered_map<std ::string,Distance> distancesFromAtoB; /*e.g distancesFromAtoB [0]=. {"chicagoToNewYork":Distance chicagoToNewYork (101.345)}*///does not work // here //Need to be inside a function //for it to work auto chicagoToNewYork (){ distancesFromAtoB [0]= {"chicagoToNewYork":Distance chicagoToNewYork (101.345)};//will work } } How does I make multiple known fixed objects inside a class from another class. More specifically for key-value pair data type. I want to do like this because they are related to each other. Also the data will never change. Should I do this in main() function? Please help I don't know what to do. Thanks :)
As Stephen Newell says in the comment, use constructors #include <unordered_map> #include <string> class Distance{ private: float km; public: // add constructor to set members Distance(float km):km{km} { } //some member functions like //rounding off }; class Payment{ private: // define map std::unordered_map<std::string,Distance> distancesFromAtoB; public: // use constructor to initialize map Payment(): distancesFromAtoB{{"chicagoToNewYork",{101.345}}, {"earth to mars", {202830000}}} { } };
72,695,497
72,697,444
How is `std::cout` implemented?
std::cout is an instance of std::ostream. I can see the declaration of std::cout in a file named /usr/include/c++/7/iostream: extern ostream cout; /// Linked to standard output And std::ostream is defined by typedef std::basic_ostream<char> std::ostream. What's more, it seems that you can't create an instance of std::ostream. See this demo code snippet: #include<iostream> int main() { std::ostream os; return 0; } Here is what the compiler complains about the code snippet above: In file included from /opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/iostream:39:0, from <source>:1: /opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/ostream: In function 'int main()': /opt/compiler-explorer/gcc-4.9.0/include/c++/4.9.0/ostream:384:7: error: 'std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char; _Traits = std::char_traits<char>]' is protected basic_ostream() ^ <source>:5:18: error: within this context std::ostream os; ^ The question arises, since the std::basic_ostream<_CharT, _Traits>::basic_ostream() is marked protected, how std::cout is created? This link on CppReference seems not very meaningful. It does not clearly tell me how std::cout is implemented and how std::cout is created by the constructor of std::ostream. As far as I can see, the most related information is: The global objects std::cout and std::wcout control output to a stream buffer of implementation-defined type (derived from std::streambuf), associated with the standard C output stream stdout. And nothing more. I am working on Ubuntu with gcc 4.9 Thanks to @NathanPierson. He told me that std::basic_ostream has a constructor that takes a pointer to a std::basic_streambuf object.std::cout is initialized using a pointer to an instance of some implementation-defined derived class of std::basic_streambuf. , which moves me closer to the answer.
how std::cout is created? First things first, from https://en.cppreference.com/w/cpp/io/ios_base/Init : std::ios_base::Init This class is used to ensure that the default C++ streams (std::cin, std::cout, etc.) are properly initialized and destructed. [...] The header <iostream> behaves as if it defines (directly or indirectly) an instance of std::ios_base::Init with static storage duration: [...] Meh, let's do a real code example. I will be using GCC C++ library. From https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/std/iostream#L73 , this is the important part: // For construction of filebuffers for cout, cin, cerr, clog et. al. static ios_base::Init __ioinit; Now we jump to the constructor of ios_base::Init class, in https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/src/c%2B%2B98/ios_init.cc#L85 : ios_base::Init::Init() { if (__gnu_cxx::__exchange_and_add_dispatch(&_S_refcount, 1) == 0) { // Standard streams default to synced with "C" operations. _S_synced_with_stdio = true; new (&buf_cout_sync) stdio_sync_filebuf<char>(stdout); new (&buf_cin_sync) stdio_sync_filebuf<char>(stdin); new (&buf_cerr_sync) stdio_sync_filebuf<char>(stderr); // The standard streams are constructed once only and never // destroyed. new (&cout) ostream(&buf_cout_sync); new (&cin) istream(&buf_cin_sync); new (&cerr) ostream(&buf_cerr_sync); new (&clog) ostream(&buf_cerr_sync); cin.tie(&cout); cerr.setf(ios_base::unitbuf); // _GLIBCXX_RESOLVE_LIB_DEFECTS // 455. cerr::tie() and wcerr::tie() are overspecified. cerr.tie(&cout); The _S_refcount is there for when you would call ios_base::Init::Init(); manually from a constructor of a static class, it protects against double initialization. The stdio_sync_filebuf is an internal buffer for istream/ostream and it is meant to handle cstdio FILE* operations to get/put input/output data, with implementation here https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/ext/stdio_sync_filebuf.h#L56 . It inherits from std::basic_streambuf. So cout is constructed in-place with stdio_sync_filebuf<char> as parameter. It is the first constructor mentioned here https://en.cppreference.com/w/cpp/io/basic_ostream/basic_ostream . Now, because the stuff is constructed in-place, you might wonder how is the memory allocated? From https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/src/c%2B%2B98/globals_io.cc#L50 : // Standard stream objects. // NB: Iff <iostream> is included, these definitions become wonky. typedef char fake_istream[sizeof(istream)] __attribute__ ((aligned(__alignof__(istream)))); typedef char fake_ostream[sizeof(ostream)] __attribute__ ((aligned(__alignof__(ostream)))); fake_istream cin; fake_ostream cout; fake_ostream cerr; fake_ostream clog; The objects are just empty char buffers of proper size and proper alignment. And yes, you can construct ostream yourself, with __gnu_cxx::stdio_sync_filebuf on GCC: #include <fstream> #include <ext/stdio_sync_filebuf.h> int main() { __gnu_cxx::stdio_sync_filebuf<char> mybuf_cout_sync(stdout); std::ostream os(&mybuf_cout_sync); os << "Hello world!\n"; return 0; } Or, to be portable, you would write your own class that inherits from std::streambuf and construct ostream from it yourself. There are many examples online, like for example here https://stackoverflow.com/a/51250032/9072753 .
72,695,765
72,695,844
does making static inline inside namespace is redundant
is there any significance of making a variable and function inline and static inside a namespace. For example consider following 2 files: consider first header file // header1.h #include <string> #include <iostream> namespace First { static inline std::string s {"hi"}; static inline void print(std::string str) { std::cout << str << std::end; } } and consider following second header file // header2.h #include <string> #include <iostream> namespace Second { std::string s {"hi"}; void print(std::string str) { std::cout << str << std::end; } } Does compiler see two codes differently or they introduce similar behavior ?
Do not namespace variables and functions have internal linkage, like unnamed namespace ? No, your assumption that namespace(named namespaces) variables and functions by default have internal linkage is incorrect. Does compiler sees two codes differently or they introduce similar behavior ? The one with thestatic keyword have internal linkage while the other(in header2.h) have external linkage. That is, the variable s in header1.h and header2.h are distinct from each other. Similarly, the functions are also different from each other. header1.h namespace First { static inline std::string s {"hi"}; //s has internal linkage static inline void print(std::string str) //print has internal linkage { std::cout << str << std::end; } } header2.h namespace Second { std::string s {"hi"}; //s has external linkage void print(std::string str) //print has external linkage { std::cout << str << std::end; } }
72,696,098
72,696,395
Does this function vector<int> help(257, -1); creates 257 vectors with -1 elements each?
As I am referring this code from someone else.This is the solution of longest substring without repeating elements.So why are we using only (257,-1) over here?Can we use more than 257 over here or what? class Solution { public: int lengthOfLongestSubstring(string s) { vector<int> help(257, -1); int n = s.size(), ans = 0, curr = 0; for (int i = 0; i < n; i++) { if (help[s[i]] != -1) { int temp = help[s[i]]; for (int x = curr; x <= temp; x++) { help[s[x]] = -1; } curr = temp+1; } help[s[i]] = i; ans = max(ans, i-curr+1); } return ans; } };
Does this function vector help(257, -1); creates 257 vectors with -1 elements each? No, it creates 1 vector with 257 values that are all initialized to -1. See https://en.cppreference.com/w/cpp/container/vector/vector constructor #3. The first parameter is count of elements, the second is the initial value for each element. So why are we using only (257,-1) over here? I'm not entirely sure about this and you need to ask the author to be absolutely sure. It looks like each element of the vector stores the index of the last occurence of a character: help[s[i]] = ... s[i], which is used as index to help here, will return a char, which can take 256 different values. With this in mind, we can see that the largest possible index will be 255. That's where the size comes from (though 256 should suffice). But it's not that easy: When input is restricted to ASCII-characters (0-127) this will work, however C++ allows char to be a signed type, i.e. on some systems char can be -128 to 127 instead of 0 to 255 which the author apparently expects. In this case, on some system, for certain inputs, you would try access a negative index on help, which is undefined behaviour. See also https://en.cppreference.com/w/cpp/language/types for more details on char.
72,696,384
72,696,853
How can I deal with a fat interface?
Say I have a big interface IShape of which Circle, Square, Triangle... inherit from. IShape has become very big, and has functions dealing with unrelated topics: for example, many for dimensions calculation, others for moving and animations, others for colouring, etc. This is against the Interface Segregation and Single Responsibility Principles, so I was trying to find the design pattern that better suits my case, but I am not sure about what is the best way for me to proceed. I was thinking in breaking IShape in smaller interfaces: IDimensions, IMovement, IColour... and then making Circle, Square and Triangle inherit from them. This would solve the problem of the fat interface (although the implementations would still be very big). What is the approach I should follow?
One approach is to keep the object (IShape) fairly "dumb" (keeping track of its internal state only, plus boilerplate access functions) and then add free-standing functions acting on it in more involved ways. In some contexts it might be useful to integrate these functions into class interfaces of their own (particularly if the functionality can be grouped well and requires some internal state), but in my opinion and experience, there's nothing wrong with a library of free-standing functions acting on objects. Note for example that large parts of the STL are made up by non-class functions. edit: Note that free-standing functions are basically automatically re-entrant (thread safe). With member functions, you have to pay more attention that the object state does not change, you might have to lock some sections, and so on. edit2: I generally try to favor composition of objects (object A "has an" object B) over inheritance (object A "is a type of" object B). When you think about it, a square (which "is" a shape) might "have" a color, but it "is" not a color. Also, think hard about on which level you compose objects: Does every Shape have a color and/or dimensions (in which case the Shape base class should have Color and Size/Polygon/Geometry/BoundingBox/... members), or do you want to keep the Shape interface more abstract in your code ecosystem (in which case concrete geometric shapes inherit from (abstract) Shape and additionally have further concrete properties, such as Size and Color)? This (and the concrete implementation of e.g. Size/Geometry) depends mostly on what you want to do with your shape-like objects.
72,697,962
72,750,127
Resizing window(framebuffer) without stretching the rendered content, (2D orthographic projection)
Im trying to retain the ratio and sizes of the rendered content when resizing my window/framebuffer texture on which im rendering exclusively on the xy-plane (z=0) and would like to have an orthographic projection. Some general questions, do i need to resize both glm::ortho and viewport, or just one of them? Do both of them have to have the same amount of pixels or just the same aspect ratio? What about their x and y offsets? I understand that i need to update the texture size. What i have tried (among many other things): One texture attachment on my framebuffer, a gl_RGB on GL_COLOR_ATTACHMENT0. I render my framebuffers attached texture to a ImGui window with imgui::image(), When this ImGui window is resized I resize the texture assignent to my FBO using this: (i do not reattach the texture with glFramebufferTexture2D!) void Texture2D::SetSize(glm::ivec2 size)` { Bind(); this->size = size; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, size.x, size.y, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); Unbind(); } I also update the member variable windowSize. In my renderingloop (for the Framebuffer) i use view = glm::lookAt(glm::vec3(0, 0, 1), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0)); glm::vec2 projWidth = windowSize.x; glm::vec2 projHeight = windowSize.y; proj = glm::ortho(-projWidth/2, projWidth/2, -projHeight/2, projHeight/2, -1.f, 1.f); shaderProgram.SetMat4("view", view, 1); shaderProgram.SetMat4("proj", proj, 1); shaderProgram.SetMat4("world", world, 1); // world is identity matrix for now glViewport(-windowSize.x/2, -windowSize.y/2, windowSize.x, windowSize.y); Now i now do have some variables here that i use to try to implement paning with but i first want to get resizing to work correctly. EDIT: ok i have now tried different parameters for the viewport and orthographic projection matrix: auto aspect = (float)(windowSize.x)/(float)windowSize.y; glViewport(0, 0, windowSize.x, windowSize.y); proj = glm::ortho<float>(-aspect, aspect, -1/aspect, 1/aspect, 1, -1); Resizing the window still stretches my renderTexture, but now it does it uniformely, x is scaled as much as y. My square sprites remain sqares, but becomes smaller as i decrease the window size. GIF
I believe there were problems with my handling of FBOs as i have now found a satisfactory solution, one that also seems to be the obvious one. Simply using the width and height of the viewport (and FBO attached texture) like this: proj = glm::ortho<float>(-zoom *viewportSize.x/(2) , zoom*viewportSize.x/(2) , -zoom*viewportSize.y/(2), zoom*viewportSize.y/(2), 1, -1); You might also want to divide the four parameters by a constant (possibly much larger than 2) to make the zooming range more natural around 1. While i tried this exact code before, I actually did not recreate the framebuffer, but simply used glTexImage2D(); on the attached texture. It seems as though one need to delete and recreate the whole Framebuffer, and this was also stated to be safer on some posts here on SO, but I never found any sources saying that it was actually required. So, lesson learnt, delete and create a new framebuffer. Window resizing is not something that happens very often.
72,698,375
72,698,521
Template function to wrap any function passed to it in C++
I am trying to use libgit2, and thought it would be nice to wrap the calls with something that will throw an exception for me instead. My philosophy was that I would then be able to invoke functions that have a common return typ. I figured I would be able to do it with a templated function but I am running into some issues: template<typename F, typename... Args> inline void invoke(Args&&... args) { git_error_code errCode = F(std::forward<Args>(args)...); if (errCode != GIT_OK) { throw GitErrorException(errCode); } } This generated some compiler warnings that I was not using a valid type so I figured that I could also use an alias instead: template<typename ... Args> using F = int (*)(Args&&... args); template<F f, typename... Args> inline void invoke(Args&&... args) { git_error_code errCode = f(std::forward<Args>(args)...); if (errCode != GIT_OK) { throw GitErrorException(errCode); } } But that also did not work when using the code as follows: Git::invoke<git_branch_name>(&name, _ref); Should I really have to rely on a macro instead here?
To have following syntax Git::invoke<git_branch_name>(&name, _ref); You need (C++17) template<auto F, typename... Args> void invoke(Args&&... args) { git_error_code errCode = F(std::forward<Args>(args)...); if (errCode != GIT_OK) { throw GitErrorException(errCode); } } For c++14, you might do instead template<typename F, typename... Args> void invoke(F f, Args&&... args) { git_error_code errCode = f(std::forward<Args>(args)...); if (errCode != GIT_OK) { throw GitErrorException(errCode); } } with usage Git::invoke(&git_branch_name, &name, _ref);
72,698,425
72,698,517
Undefined Reference to Time::Time(int,int,int)
An error appeared while I was testing the driver code. The compiler raised such an error: undefined reference to Time::Time(int, int, int) AND undefined reference to Time::setTime(int, int, int) Why did the Code::Blocks IDE raise this error? Is it due to the main or any declaration or definition errors? Please point out my error. TIME.H # ifndef TIME1_H # define TIME1_H class Time { public: Time(int, int, int); // Default constructor void setTime(int, int, int); // Set hour, minute, second void printMilitary(); void printStandard(); private: int hour; int minute; int second; }; # endif TIME.CPP # include <iostream> # include "TIME.H" using namespace std; // Implementing the functions void Time::setTime(int hour, int minute, int second) { setTime(hour, minute, second); } void Time::printMilitary() { if(hour >= 1200 && hour <= 2359) { hour-1200; cout << hour << ":" << minute; } if(hour < 1200 && hour >= 100) { cout << hour << ":" << minute << ":" << second << " AM"; } else { cout << hour << ":" << minute << ":" << second; } } void Time::printStandard() { if(hour) { cout << hour << ":" << minute << ":" << second; { } } MAIN.CPP # include <iostream> # include "TIME.H" using namespace std; int main() { Time a(0, 0, 0); a.setTime(12, 23, 18); return 0; } Are there any links to help? When I tried the working demo posted by @Annop Raya, everything was fine when I ran the code. But when I try this code in Code::Blocks, it raised a few errors at the implementation file. The errors are shown below: Line 6 error: 'Time' does not name a type; did you mean 'time'? Line 11 error: 'Time' has not been declared Line 17 error: 'Time' has not been declared Line 17 In function 'void printMilitary()': Line 19 'hour' was not declared in this scope All the private member variables gets the same error, what's wrong? In the main file, the compiler still returns the same error, so is there a solution for this?
The problem is that you've not implemented the constructor Time::Time(int, int, int) in your source file. To solve this just add a definition for Time::Time(int, int, int). TIME.CPP //implmentation for constructor that was not there before Time::Time(int phour, int pminute, int psecond): hour(phour), minute(pminute), second(psecond) { } //other code Working demo
72,699,309
72,699,823
Why does cin.fail() ignore periods and commas in "while" loop? What's a simple way to error check input?
Sorry it sounds stupid, but I'm just getting started in C++ programming... My input checking loop works fine if I want it to accept 'float' numbers, but outputs some weird results if it has to accept only 'int' numbers. EDIT: Tutorials I read/watched assumed that user wouldn't input things like that, which is dumb... #include <iostream> #include <limits> using namespace std; // input with check int num(int i) { int x=0; cout<<"Enter #"<<i+1<<": "; cin>>x; while(cin.fail()) { cin.clear(); cin.ignore(numeric_limits<streamsize>::max(),'\n'); cout<<"Enter INTEGER #"<<i+1<<": "; cin>>x; } return x; } int main() { int i, min=0, max=0, n=3; int arr[3]; // save input into array for(i=0; i<n; i++) { arr[i] = num(i); } // find 'max' & 'min' max = arr[0]; for(i=1; i<n; i++) { if(max < arr[i]) { max = arr[i]; } } min = arr[0]; for(i=1; i<n; i++) { if(min > arr[i]) { min = arr[i]; } } cout << endl << "MAX = " << max; cout << endl << "MIN = " << min; return 0; } For example if I type in 5.2 it takes in the 5, skips one loop and puts out error message on the next loop. Output: Enter #1: 2 Enter #2: 5.5 Enter #3: Enter INTEGER #3: g Enter INTEGER #3: -2 MAX = 5 MIN = -2 EDIT2: I did some digging and I found something that kind of works for my use and is simple enough for my skill level, but still has some quirks. Function just filters out anything that isn't characters you specify between the quotes and checks if '-' is as the first character. bool isNumeric(string const &str) { if(str.find_last_of("-")==0 || str.find_last_of("-")==SIZE_MAX) { return !str.empty() && str.find_first_not_of("-0123456789") == string::npos; } else { return 0; } } int num(int i) { string str; cout << "Enter #" << i+1 << ": "; getline(cin,str); while(isNumeric(str)==0) { cout << "Enter INTEGER #" << i+1 << ": "; getline(cin,str); } return stoi(str); // convert string to integer } Source: https://www.techiedelight.com/determine-if-a-string-is-numeric-in-cpp/ - method #3
cin read '5'-> integer -> get -> cin read '.' -> not integer -> not get -> n = 5 -> recall func -> cin read '.' -> not integer -> invalid -> cin fail if you write like this: int a; cin >> a; double b; cin >> b; cout << a << " " << b; with input 5.5, the output will be 5 0.5. If you want check if your input is integer, you can write like this: bool isInteger(char* s, int length) { if (length == 0) return false; if (s[0] != '-' && s[0] != '+' && !isdigit(s[0])) return false; for (int i = 1; i < length;) if (!isdigit(s[i++])) return false; return true; } int num(int i) { char c[11]; cout << "Enter #" << i + 1 << ": "; cin.getline(c, 11); while (!isInteger(c, cin.gcount() - 1)) { cout << "Enter INTEGER #" << i + 1 << ": "; cin.getline(c, 11); } return stoi(c); }
72,701,129
72,701,232
A constexpr function that calculates how deep a std::vector is nested
Is there a way to write a constexpr function that returns how deep a std::vector is nested? Example: get_vector_nested_layer_count<std::vector<std::vector<int>>>() // 2 get_vector_nested_layer_count<std::vector<std::vector<std::vector<float>>>>() // 3
The easy way is to use recursion #include <vector> template<class T> constexpr bool is_stl_vector = false; template<class T, class Alloc> constexpr bool is_stl_vector<std::vector<T, Alloc>> = true; template<class T> constexpr std::size_t get_vector_nested_layer_count() { if constexpr (is_stl_vector<T>) return 1 + get_vector_nested_layer_count<typename T::value_type>(); else return 0; }; Demo
72,701,223
72,701,573
(non)ambiguous static overload within templated class
My class template NodeMaker has 3 static member function templates called create_node which are distinguished by their argument(s) using C++20 concepts. When calling NodeMaker<>::create_node(x) from main() everything works as I intended, but when calling create_node from another member function, GCC claims ambiguous overload, and I fail to understand why. #include <utility> #include <type_traits> template<class F> concept NodeFunctionType = std::invocable<std::remove_reference_t<F>, int>; template<class T> concept ExtracterType = requires { typename T::I_am_an_extracter; }; template<class T = int> struct NodeMaker { template<class... Args> static constexpr auto create_node(Args&&... args) { return new T(std::forward<Args>(args)...); } template<NodeFunctionType DataMaker> requires (!ExtracterType<DataMaker>) static constexpr auto create_node(DataMaker&& data_maker) { return create_node(); } // line 13 template<ExtracterType DataMaker> requires (!NodeFunctionType<DataMaker>) static constexpr auto create_node(DataMaker&& data_maker) { return create_node(); } // line 16 void do_something() { const auto target = create_node(0); //this does not work in gcc } }; int main(const int argc, const char** argv) { const auto target = NodeMaker<>::create_node(0); //but this works } GCC errors out when compiling: <source>: In member function 'void NodeMaker<T>::do_something()': <source>:19:36: error: call of overloaded 'create_node(int)' is ambiguous 19 | const auto target = create_node(0); <source>:10:25: note: candidate: 'static constexpr auto NodeMaker<T>::create_node(Args&& ...) [with Args = {int}]' 10 | static constexpr auto create_node(Args&&... args) { return new T(std::forward<Args>(args)...); } <source>:13:25: note: candidate: 'static constexpr auto NodeMaker<T>::create_node(DataMaker&&) [with DataMaker = int]' 13 | static constexpr auto create_node(DataMaker&& data_maker) { return create_node(); } <source>:16:25: note: candidate: 'static constexpr auto NodeMaker<T>::create_node(DataMaker&&) [with DataMaker = int]' 16 | static constexpr auto create_node(DataMaker&& data_maker) { return create_node(); } But, 13 | static constexpr auto create_node(DataMaker&& data_maker) cannot possibly match because int does not satisfy NodeFunctionType and 16 | static constexpr auto create_node(DataMaker&& data_maker) cannot possibly match because int does not satisfy ExtracterType. Further, under no circumstances can both function templates match since their constraints are obviously mutually exclusive. So my question would be: why can't GCC disambiguate the call from a member function (but can do it when called from outside the class)? PS: see godbolt.
This seems to be a gcc bug. Here is the submitted bug report. It seems that gcc requires the call to the static method create_node to be explicitly qualified with NodeMaker<>:: even from inside the non-static member function do_something. You can confirm that this is the case by adding NodeMaker<>:: and you'll see that it then works in gcc. void do_something() { //----------------------vvvvvvvvvvvvv--------------->added this qualification const auto target = NodeMaker<>::create_node(0); //works now in gcc } Demo Note also that if you use NodeMaker<T>::create_node(0); from inside do_something then the issue will reappear.
72,701,502
72,709,441
How to declare a policy class that does nothing to a string, has consistent signature with other policies and is evaluated at compile-time
I am putting together a set of policy classes that operate a number of operations to a string. I would like these policies to be exchangeable, but the "do nothing" policy is problematic too me, as: I don't see how to avoid copy using move semantic while maintaining the same (non-move) interface with the sister policies The compiler should know that the call to the policy can be inlined and evaluated at compile time, but it does not accept constexpr because the return type is a string. #include <string> #include<regex> #include<cassert> /// /// @brief Do not change anything /// struct identity { static std::string edit(std::string&& s) // can not use constexpr: return type not a literal { return std::move(s); } }; /// /// @brief Template class. /// template<unsigned int N> struct remove_comments_of_depth {}; /// /// @brief Do not remove anything /// template<> struct remove_comments_of_depth<0> : identity {}; /// /// @brief Remove all comments substrings contained between square brackets /// /// @note Assumes that text is well formatted so there are no such things like [[]] or unclosed bracket /// template<> struct remove_comments_of_depth<1> { static std::string edit(const std::string& s) { return std::regex_replace(s, std::regex(R"(\[[^()]*\])"), ""); } }; int main(int argc, char *argv[]) { std::string s = "my_string[this is a comment]"; auto copy = s; assert(remove_comments_of_depth<1>::edit(s) == "my_string"); assert(remove_comments_of_depth<0>::edit(std::move(copy)) == s); // <<< how to avoid this call to std::move } What is the "standard" way to go in this kind of situation?
What you want here is reduce unnecessary copy and don't use std::move when calling edit. Why not just return a const reference? struct identity { static const std::string& edit(const std::string& s) { return s; } }; std::string s = "my_string[this is a comment]"; assert(remove_comments_of_depth<0>::edit("my_string[this is a comment]") == "my_string[this is a comment]"); assert(remove_comments_of_depth<0>::edit(s) == "my_string[this is a comment]"); See Online Demo As to your second question, since C++20, std::string can be a literal type. struct identity { constexpr static std::string edit(std::string&& s) { return s; } }; static_assert(remove_comments_of_depth<0>::edit("my_string[this is a comment]") == "my_string[this is a comment]"); It's totally fine in C++20, see Demo. But since your variable s can't be constexpr (it's created at run-time), there's no big help here.
72,702,026
72,735,797
Pybind11 cv::Mat from C++ to Python
I want to write a function that gets an image as parameter and returns another image and bind it into python using pybind11. The part on how to receive the image as parameter is nicely solve thanks to this question. On the other hand, the returning image is a bit tricky. Here my code (I try flipping the image using a cv function as an example): py::array_t<uint8_t> flipcvMat(py::array_t<uint8_t>& img) { auto rows = img.shape(0); auto cols = img.shape(1); auto channels = img.shape(2); std::cout << "rows: " << rows << " cols: " << cols << " channels: " << channels << std::endl; auto type = CV_8UC3; cv::Mat cvimg2(rows, cols, type, (unsigned char*)img.data()); cv::imwrite("/source/test.png", cvimg2); // OK cv::Mat cvimg3(rows, cols, type); cv::flip(cvimg2, cvimg3, 0); cv::imwrite("/source/testout.png", cvimg3); // OK py::array_t<uint8_t> output( py::buffer_info( cvimg3.data, sizeof(uint8_t), //itemsize py::format_descriptor<uint8_t>::format(), 3, // ndim std::vector<size_t> {rows, cols , 3}, // shape std::vector<size_t> {cols * sizeof(uint8_t), sizeof(uint8_t), 3} // strides ) ); return output; } And I call it from python as: img = cv2.imread('/source/whatever/ubuntu-1.png') img3= opencvtest.flipcvMat(img) My input image is an RGB image. Both images that are written with cv::imwrite are correct (the original is the same as the input and the 2nd is correctly flipped) The Problem is On the python side, the returning image seems to be wrong-aligned (I can distinguish some shapes but the pixels are not in the right place. My guess is that I have a problem while creating the py::buffer_infobut I cannot find it. What could I be doing wrong?
Yes it indeed is a problem with py::buffer_info, the strides to be more precise Instead of: { cols * sizeof(uint8_t), sizeof(uint8_t), 3 } The strides should be: { sizeof(uint8_t) * cols * 3, sizeof(uint8_t) * 3, sizeof(uint8_t)}
72,702,138
72,703,125
Qt cannot write to file. File exists, isn't open, "Unknown error" (Windows OS)
Would really appreciate your help. I'm new to Qt and C++. I managed to get this working previously, but for some reason am no longer able to do so. I haven't touched anything to do with the writing of files, but all functions pertaining to file writing no longer seem to function. Here's an example of one of the simpler write functions: #include <QStringList> #include <QDir> #include <QFile> #include <QString> #include <QTextStream> void HandleCSV::writeToPIDCSV(UserAccount newUser) { // Storing in userPID db QString filePath = returnCSVFilePath("dbPID"); qDebug() << "File path passsed to writeToPIDCSV is " << filePath; // Open CSV filepath retrieved from associated dbName QFile file(filePath); if (!file.open(QIODevice::ReadWrite | QIODevice::Append)) { qDebug() << file.isOpen() << "error " << file.errorString(); qDebug() << "File exists? " << file.exists(); qDebug() << "Error message: " << file.error(); qDebug() << "Permissions err: " << file.PermissionsError; qDebug() << "Read error: " << file.ReadError; qDebug() << "Permissions before: " << file.permissions(); // I tried setting permissions in case that was the issue, but there was no change file.setPermissions(QFile::WriteOther); qDebug() << "Permissions after: " << file.permissions(); } // if (file.open(QIODevice::ReadWrite | QIODevice::Append)) else { qDebug() << "Is the file open?" << file.isOpen(); // Streaming info back into db QTextStream stream(&file); stream << newUser.getUID() << "," << newUser.getEmail() << "," << newUser.getPassword() << "\n"; } file.close(); } This gets me the following output when run: File path passsed to writeToPIDCSV is ":/database/dummyPID.csv" false error "Unknown error" File exists? true Error message: 5 Permissions err: 13 Read error: 1 Permissions before: QFlags(0x4|0x40|0x400|0x4000) Permissions after: QFlags(0x4|0x40|0x400|0x4000) The file clearly exists and is recognised when run, but for some reason file.isOpen() is false, and the permissions show that the user only has read (not write) permissions that are unaffected by permission settings. Would someone have a clue as to why this is happening? Many thanks in advance Update Thanks @chehrlic and @drescherjm - I didn't realise that I can only read but not write to my resource file! Using QStandardPaths allows me to write to my AppDataLocation. I've included the code below for others who might encounter similar issues, adapted from https://stackoverflow.com/a/32535544/9312019 #include <QStringList> #include <QDir> #include <QFile> #include <QString> #include <QTextStream> #include <QStandardPaths> void HandleCSV::writeToPIDCSV(UserAccount newUser) { auto path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); if (path.isEmpty()) qFatal("Cannot determine settings storage location"); QDir d{path}; QString filepath = returnCSVFilePath("dbPID"); if (d.mkpath(d.absolutePath()) && QDir::setCurrent(d.absolutePath())) { qDebug() << "settings in" << QDir::currentPath(); QFile f{filepath}; if (f.open(QIODevice::ReadWrite | QIODevice::Append)) { QTextStream stream(&f); stream << newUser.getUserFirstName() << "," << newUser.getUserIDNumber() << "\n"; } } } Am now testing to make this work with my Read functions. If there's any way to be able to write to the Qt program's folder (or build folder), I'd really appreciate it!
You can not write to a Qt resource. If you want to update/write to a file you should put the file into a writeable filesystem. To e.g. place it in the appdata folder you can use QStandardPaths::writeableLocation(QStandardPaths::ApplicationsLocation)
72,702,243
72,702,331
Creating a very basic calculator in C++
I'm extremely new to C++, I was following a tutorial and wanted to go a bit off what the course said, I attempted to make a basic calculator that instead of just being able to add could subtract, divide and multiply but it still seems to only be able to add, why is this? int num1, num2; double sum; int addType; cout << "Type a number: "; cin >> num1; cout << "Type a second number: "; cin >> num2; cout << "Do you want to 1. add, 2. subtract, 3. divide or 4. multiply: "; cin >> addType; if (int addType = 1) { sum = num1 + num2; } else if (int addType = 2) { sum = num1 - num2; } else if (int addType = 3) { sum = num1 / num2; } else if (int addType = 4) { sum = num1 * num2; } cout << "Your total is: " << sum; }
You are creating new variable in if condition part, update condition part to check if it is equal to something with addType == x int num1, num2; double sum; int addType; cout << "Type a number: "; cin >> num1; cout << "Type a second number: "; cin >> num2; cout << "Do you want to 1. add, 2. subtract, 3. divide or 4. multiply: "; cin >> addType; if (addType == 1) { sum = num1 + num2; } else if (addType == 2) { sum = num1 - num2; } else if (addType == 3) { sum = num1 / num2; } else if (addType == 4) { sum = num1 * num2; } cout << "Your total is: " << sum; }
72,702,485
72,702,612
Function style casting using the `new T()` operator in C++
Here is an example of a simple function style casting done by int(a): float a = 5.0; int b = int(a); More info from cpprefrenece: The functional cast expression consists of a simple type specifier or a typedef specifier followed by a single expression in parentheses. I have 2 questions: 1) would using the new operator still count as a functional cast? int* b = new int(a); 2) Assuming test is a class, then test t = test(1); is a function style casting to test but test t = test(1, 2); isn't because it has more than 1 expression in parenthesis?
would using the new operator still count as a functional cast? No, the use of the new operator(like you used in your example) is not a use case of functional cast. test t = test(1, 2); isn't because it has more than 1 expression in parenthesis? Both test t = test(1); and test t = test(1,2); are copy initializations. Now, the subexpression test(1) is indeed a functional cast where the appropriate test constructor will be used. While the subexpression test(1, 2) is not as it has more than a single expression inside parenthesis.
72,702,574
72,709,859
Does bitfield count as common initial sequence with a whole int of the same type?
I was wondering if the following was valid C++: union id { struct { std::uint32_t generation : 8; std::uint32_t index : 24; }; std::uint32_t value; }; I want this so I can access both generation and index separately, which keeping access to the whole number. Since they all are std::uint32_t, this shouldn't be UB right? I plan to use it like that: auto my_id = id{ .generation = 1, .index = 4, }; auto my_id_value = std::uint32_t{id.value}; If it is UB, is there another way to make this work and valid according to the C++ standard?
By resolution of CWG 645 (for C++11; not sure whether it is supposed to apply to C++98 as DR) the common initial sequence requires corresponding non-static data members or bit-fields in the two classes (by declaration order) to either be both bit-fields (of the same width) or neither be bit-fields. The wording for that can still be found in [class.mem.general]/23 in the current draft, including an example stating clearly that a bit-field of the same type as a non-static data member will not be part of the common initial sequence. Therefore the exceptional rule in [class.mem.general]25 allowing access to inactive members in the common initial sequence of standard-layout class members in a union doesn't apply in your case and reading id.value in auto my_id_value = std::uint32_t{id.value}; has undefined behavior.
72,702,684
72,703,386
Is there any other way besides MAPI to know two different email addresses belong to one Outlook account?
I am trying to integrate my application with Outlook. I have referred to Integrating IM applications with Office. I met an issue when an Outlook/Office account has two different email addresses, Outlook will call the IContactManager.GetContactByUri() API twice with the two email addresses. Because I don't know the two email addresses belongs to one account, I will return different property values of the two emails to Outlook, which finally lead to Outlook showing an unexpected state on the contact page. For example, one Outlook account Glider has two email addresses glider123@xxx.com and gliderABC@xxx.com. In my application, account glider123@gmail.com is in the presence state of busy, while gliderABC@xxx.com is in the presence state of free. Because I don't know glider123@xxx.com and gliderABC@xxx.com belong to one Outlook account Glider, when Outlook calls the GetContactByUri() API, I will create two IContact instances on my local, and they will return different presence state values to Outlook. Finally, on the contact page of Glider in Outlook, its presence state is free. I know MAPI can solve this, but is there any other way?
For an Exchange account, multiple proxy addresses are stored in the PR_EMS_AB_PROXY_ADDRESSES MAPI property (DASL name http://schemas.microsoft.com/mapi/proptag/0x800F101F), which can be accessed in Outlook Object Model using AddressEntry.PropertyAccessor.GetProperty.
72,702,736
72,703,242
Is there a better way to generic print containers in C++20/C++23?
I use the following code to print generic C++ containers and exclude strings (thanks to this SO answer). #include <iostream> #include <vector> template <typename T, template <typename ELEM, typename ALLOC = std::allocator<ELEM>> class Container> std::ostream &operator<<(std::ostream &out, const Container<T> &container) { out << "["; bool first = true; for (const auto &elem : container) { if (first) first = false; else out << ", "; out << elem; } return out << "]"; } int main() { std::vector<std::vector<int>> v{{1, 2}, {3, 4}}; std::cout << v << "\n"; return 0; } Which prints the 2d vector correctly [[1, 2], [3, 4]] And does not mess with outputting strings. Is there a cleaner (concept-based?) way to write the template in C++20 or C++23?
With concepts, you might require only container/range types and discard string-like types, something like: template <typename Container> requires std::ranges::input_range<const Container> && (!std::convertible_to<const Container, std::string_view>) std::ostream &operator<<(std::ostream &out, const Container& container) { out << "["; const char* sep = ""; for (const auto &elem : container) { out << sep << elem; sep = ", "; } return out << "]"; } Demo With the caveats that generic template should involve at least one user type. Else it might conflict with possible future operator<< for std (or other library) containers...
72,703,052
72,703,130
Why the output is "abBA"?
I have this code: #include <iostream> class A { public: A() { std::cout << 'a'; } ~A() { std::cout << 'A'; } }; class B { public: B() { std::cout << 'b'; } ~B() { std::cout << 'B'; } A a; }; int main() {B b; } Why is it creating object A a; is done before executing B b; arguments? Is there a priority sequence?
Class members are initializing before executing the constructor of B. Same as: B() : a() { std::cout << "B"; }
72,703,255
72,703,319
Unable to Allocate large cpp std::vector that is less than std::vector::max_size()
I am trying to allocate a vector<bool> in c++ for 50,000,000,000 entries; however, the program errors out.terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc (or in the online compiler it just ends). I initially thought this was due to too large a size; however, v1.maxsize() is greater than 50GB for me. What's confusing though, is when I reduce the # of entries it works fine. Question: What could be the root cause of this considering that the number of entries is less than maxsize of a vector? Other questions/answers have suggested that similar issues are due to being on a 32 bit cpu; however I have a 64bit. #include <iostream> #include <vector> using namespace std; int main() { long size = 50000000000; std::vector<bool> v1; std::cout << "max_size: " << bool(v1.max_size() > 50000000000) <<"vs" << size << "\n"; v1 = std::vector<bool>(size,false); cout << "vector initialised \n" << endl; cout << v1.size() << endl; } note: I am essentially trying to create a memory efficient bitmap to track if certain addresses for a different data structure have been initialized. I cant use a bitset mentioned in this post since the size isn't known at compile time.
From std::vector::max_size: This value typically reflects the theoretical limit on the size of the container, at most std::numeric_limits<difference_type>::max(). At runtime, the size of the container may be limited to a value smaller than max_size() by the amount of RAM available. This means that std::vector::max_size is not a good indication to the actual maximum size you can allocate due to hardware limitation. In practice the actual maximum size will [almost] always be smaller, depending on your available RAM in runtime. On current 64 bit systems this will always be the case (at least with current available hardware), because the theoretical size in a 64 bit address space is a lot bigger than available RAM sizes.
72,704,422
72,704,583
how to return a dynamic char array from function C++
I dont really understand pointers and how to call and create dynamic arrays despite spending the time to educate myself on them and I am running into an error on the following line: char *dArray = alphabet(N); Here on my instructions and what Im trying to do: The program first asks user to enter the number of elements for an array. Let’s call this number N. It then creates a dynamic array of size N+ 1, containing Nrandom lowercase alphabet letters between ‘a’ and ‘z’. Make sure the last element is a null character ‘\0’. – Here, make sure to use dynamic memory allocation (using new command) to allocate memory space for the array, which is exactly why we call it a dynamic array. After creating the array, the program displays the entire array. #include <stdio.h> #include <iostream> #include <algorithm> // for std::find #include <iterator> // for std::begin, std::end #include <ctime> using namespace std; char alphabet(int N) { char *dArray; dArray= new char[N+1]; dArray[N]= '\0'; int i; srand(time(NULL)); for (i=0; i<N; i++) { int r = rand()%26; char letter='a'+r; cout<<"dArray["<<i<<"] is: "<< letter<<endl; dArray[i]= letter; } return *dArray; } int main() { int arrayN; int N; printf("enter the number of elements: "); cin >> N; char *dArray = alphabet(N); for (int i=0; i<=N; i++) { cout<<"dArray["<<i<<"] "<<dArray[i]<<endl; } }
you have declared the return type wrong. it should be char * char *alphabet(int N) // <<<<==== { char *dArray; dArray= new char[N+1]; dArray[N]= '\0'; int i; srand(time(NULL)); for (i=0; i<N; i++) { int r = rand()%26; char letter='a'+r; cout<<"dArray["<<i<<"] is: "<< letter<<endl; dArray[i]= letter; } return dArray; // <<<<<<===== } but much better would be std::string or std::vector<char>
72,705,340
72,705,623
Effective way of finding GCD of 2 numbers using recursive approach
I have been recently solving a problem to find GCD/HCF of two numbers using Recursion. The first solution that came to my mind was something like given below. long long gcd(long long a, long long b){ if(!(a - b) return a; return gcd(max(a, b) - min(a, b), min(a, b)); } I saw other people's solutions and one approach was very common which was something like given below. long long gcd(long long a, long long b){ if(!b) return a; return gcd(b, a % b); } What is the difference between the Time Complexities of these two programs? How can I optimise the former solution and how can we say that the latter solution is efficient than any other algorithm?
What is the difference between the Time Complexities of these two programs? If you are talking about the time complexity, then you should consider the big-O notation. The first algorithm is O(n) and the second one isO(logn), where n = max(a, b). How can I optimise the former solution? In fact, the second algorithm is a straigtforord optimization of the first one. In the first solution, if the gap between a and b is huge, it takes many subtractions for a - b to reach the remainder a % b. So we can improve this part by using the integer modulo operation instead, which yields the second algorithm.
72,705,449
72,747,798
Visual Studio Won't Update C++ Version
I am trying to use the <filesystem> library, and for that I need C++17 or later. I went to the project properties, to General, then to "C++ language standard", and set the language to C++20. But when I compile, it says that the library is only available with C++17 or later, and doesn't let me use it. I went to the <filesystem> header document and saw that the _HAS_CXX17 macro was defined as false, which was causing the problems. I went to the location where the _HAS_CXX17 macro was defined, vcruntime.h, and tried setting it to true, but Visual Studio doesn't allow users to edit that file. This problem is puzzling to me, as I have used the <filesystem> library in other projects, and the C++ version updated without issues. I have not changed anything in my settings of the overall Visual Studio application, nor have I messed with any of its files before.
As I already suspected in the comments and as confirmed by the OP, the problem was that the OP changed the properties for a configuration and/or platform which was not the currently active one. It is quite easy to forget to select the desired one in the properties dialog since the combo boxes in the properties are not synced with the ones that determine the active configuration/platform. See the following image:
72,706,198
72,706,295
Printing a type in a namespace via {fmt} and ostream
This answer mentions how you can include <fmt/ostream.h> to have ostream-printable types recognized by {fmt}. I noticed that it doesn't work when the type is in a namespace: #include <fmt/format.h> #include <fmt/ostream.h> namespace foo { struct A {}; } std::ostream& operator<<(std::ostream& os, const foo::A& a) { return os << "A!"; } int main() { fmt::print("{}\n", foo::A{}); } This will result in the old error (before including #include <fmt/ostream.h>) for a type without a namespace again: fmt/core.h:1422:3: error: static_assert failed due to requirement 'fmt::formattable<foo::A>()' "Cannot format an argument. To make type T formattable provide a formatter<T> specialization: https://fmt.dev/latest/api.html#udt" static_assert( ^ fmt/core.h:1438:10: note: in instantiation of function template specialization 'fmt::detail::check<foo::A>' requested here return check<T>(arg_mapper<Context>().map(val)); ^ fmt/core.h:1587:23: note: in instantiation of function template specialization 'fmt::detail::make_arg<true, fmt::basic_format_context<fmt::detail::buffer_appender<char>, char>, fmt::detail::type::custom_type, foo::A, 0>' requested here data_{detail::make_arg< ^ fmt/core.h:1626:10: note: in instantiation of member function 'fmt::format_arg_store<fmt::basic_format_context<fmt::detail::buffer_appender<char>, char>, foo::A>::format_arg_store' requested here return {args...}; ^ fmt/core.h:2114:28: note: in instantiation of function template specialization 'fmt::make_args_checked<foo::A, char [4], char>' requested here const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...); ^ main.cpp:15:8: note: in instantiation of function template specialization 'fmt::print<char [4], foo::A, char>' requested here fmt::print("{}\n", foo::A{}); ^ Is there a way to make it work without implementing formatter<foo::A>?
By argument-dependent lookup, it's required to put the operator<< definition inside the foo namespace: #include <fmt/format.h> #include <fmt/ostream.h> namespace foo { struct A {}; std::ostream& operator<<(std::ostream& os, const A& a) { return os << "A!"; } } // namespace foo int main() { fmt::print("{}\n", foo::A{}); }
72,706,224
72,706,812
How do I reverse the order of the integers in a `std::integer_sequence<int, 4, -5, 7, -3>`?
Sometimes I want to reverse the values in an index_sequence and use the result to reverse the values in something tuple-like, like in this illustration which reverses the values in a constexpr std::array at compile time. #include <array> #include <cstdint> #include <utility> namespace detail { template <class T, std::size_t N, std::size_t... I> constexpr std::array<T, N> rev_arr_helper(const std::array<T, N>& arr, std::index_sequence<I...>) { return {arr[sizeof...(I) - I - 1]...}; // {arr[4-0-1], arr[4-1-1], arr[4-2-1], arr[4-3-1]} // => // {arr[3], arr[2], arr[1], arr[0]} } } // namespace detail template <class T, std::size_t N> constexpr std::array<T, N> rev_arr(const std::array<T, N>& arr) { return detail::rev_arr_helper(arr, std::make_index_sequence<N>{}); } int main() { constexpr std::array<int, 4> arr{11, 22, 33, 44}; constexpr auto rev = rev_arr(arr); static_assert(rev[0] == 44 && rev[1] == 33 && rev[2] == 22 && rev[3] == 11, ""); } Now, this approach does not work for any integer_sequence, like the one in the title. It only works for those ordered 0, 1, 2, ..., N-1 and I would like to be able to make this compile using C++14: #include <type_traits> #include <utility> int main() { std::integer_sequence<int, 4, -5, 7, -3> iseq; std::integer_sequence<int, -3, 7, -5, 4> itarget; auto irev = reverse_sequence(iseq); static_assert(std::is_same<decltype(irev), decltype(itarget)>::value, ""); } How can that be done? Here's a somewhat related Q&A collected from the comments: How do I reverse the order of element types in a tuple type?
A solution that doesn't use std::tuple is to convert to an std::array and access the corresponding indices with the help of std::make_index_sequence. namespace detail { template<typename T, T... N, std::size_t... Indices> constexpr auto reverse_sequence_helper(std::integer_sequence<T, N...> sequence, std::index_sequence<Indices...>) { constexpr auto array = std::array<T, sizeof...(N)> { N... }; return std::integer_sequence<T, array[sizeof...(Indices) - Indices - 1]...>(); } } template<typename T, T... N> constexpr auto reverse_sequence(std::integer_sequence<T, N...> sequence) { return detail::reverse_sequence_helper(sequence, std::make_index_sequence<sizeof...(N)>()); } if C++20 is available, it can be reduced to this function with the help of templated lambdas: template<typename T, T... N> constexpr auto reverse_sequence(std::integer_sequence<T, N...> sequence) { constexpr auto array = std::array { N... }; auto make_sequence = [&]<typename I, I... Indices>(std::index_sequence<Indices...>) { return std::integer_sequence<T, array[sizeof...(Indices) - Indices - 1]...>(); }; return make_sequence(std::make_index_sequence<sizeof...(N)>()); }
72,706,624
72,706,672
Possible strict aliasing violation?
I was scrolling through some posts and I read about something called the strict aliasing rule. It looked awfully close to some code I've seen in a club project, relevant snippet below. LibSerial::DataBuffer dataBuffer; size_t BUFFER_SIZE = sizeof(WrappedPacket); while(true) { serial_port.Read(dataBuffer, sizeof(WrappedPacket)); uint8_t *rawDataBuffer = dataBuffer.data(); //this part auto *wrappedPacket = (WrappedPacket *) rawDataBuffer; ... the struct definitions are: typedef struct __attribute__((__packed__)) TeensyData { int16_t adc0, adc1, adc2, adc3, adc4, adc5, adc6, adc7, adc8, adc9, adc10, adc11; int32_t loadCell0; double tc0, tc1, tc2, tc3, tc4, tc5, tc6, tc7; } TeensyData; typedef struct __attribute__((__packed__)) WrappedPacket { TeensyData dataPacket; uint16_t packetCRC; } WrappedPacket; Hopefully it's pretty obvious that I'm new to C++. So 1) is this a violation of the rule? and 2) if it is, what alternative solutions are there?
Yeah, it's a violation. The rule lets you use raw byte access (char*, unsigned char*, std::byte*) to access other data types. It doesn't let you use other data types to access arrays of raw bytes. The solution is memcpy: WrappedPacket wpkt; std::memcpy(&wpkt, dataBuffer.data(), sizeof wpkt);
72,706,894
72,707,195
Why can I use curly brackets to initialize one enum class with a value from another enum class?
I have found the following behavior of Clang-12, Clang-13 and Clang-14 with c++17 standard: enum class FOO { VALUE }; enum class BAR { VALUE }; FOO value1{BAR::VALUE}; // OK FOO value2 = BAR::VALUE; // Error Why is there a difference? I would expect enum class to be 100% type safe. Compiler Explorer
This is CWG issue 2374. In C++17, before the resolution of this issue, direct-list-initialization of an enumeration with a fixed underlying type by a single expression was specified to always be equivalent to a functional style cast. A functional style cast then would be equivalent to a static_cast and that would actually be allowed between different enumeration types (by going through the promoted underlying type). With the issue resolution this path is taken only if the initializer expression is implicitly convertible to the enumeration type, which doesn't allow for conversion between different enumeration types. That seems to have been an oversight in the resolution of a prior issue for C++17: CWG 2251 It seems that Clang decided to faithfully implement CWG 2251 and only revert this special case once CWG 2374 was resolved and the fix for the latter will be included with Clang 15. For GCC the same seems to apply before GCC 12. MSVC seems to forbid the conversion only in conformance mode (/permissive- or C++20 or later mode) and only since v19.25.
72,707,337
72,707,621
How can I decide if I want to return a pair with an integer key or string key inside a template function
I'm trying to figure out what type the template currently is, I have looked in stackoverflow but did not find a solid answer. Basically I want to create an #if #else #endif and depending on the type of the template put code. Here is my code #include <map> #include <iostream> template <typename T> #define IS_INT std::is_integral<T::first_type>::value T create_a_pair() { #if IS_INT return std::make_pair(5, typename T::second_type())); #else return T(); #endif } int main() { std::cout << create_a_pair<std::pair<int, int> >().first << std::endl; std::cout << create_a_pair<std::pair<std::string, int> >().first << std::endl; } I tried this also but I got a compile time error saying I can't use integer 5 because the type is a string. #include <map> #include <iostream> template <typename T> T create_a_pair() { if (std::is_integral<T::first_type>::value) return std::make_pair(5, typename T::second_type())); return T(); } int main() { std::cout << create_a_pair<std::pair<int, int> >().first << std::endl; std::cout << create_a_pair<std::pair<std::string, int> >().first << std::endl; }
Whenever I need some type_traits from newer C++ standards, I steal them and adapt them to the older standard (if needed). Example: namespace traits98 { struct false_type { static const bool value; }; const bool false_type::value = false; struct true_type { static const bool value; }; const bool true_type::value = true; template<class T, class U> struct is_same : false_type {}; template<class T> struct is_same<T, T> : true_type {}; template<bool B, class T = void> struct enable_if {}; template<class T> struct enable_if<true, T> { typedef T type; }; } // namespace traits98 With those, you can easily make overloads: #include <iostream> #include <string> #include <utility> using namespace traits98; template <typename F, typename S> typename enable_if<!is_same<int, F>::value, std::pair<F,S> >::type create_a_pair() { return std::pair<F,S>(); } template <typename F, typename S> typename enable_if<is_same<int, F>::value, std::pair<F,S> >::type create_a_pair() { return std::make_pair(5, S()); } int main() { std::cout << create_a_pair<int, int>().first << '\n'; std::cout << create_a_pair<std::string, int>().first << '\n'; }
72,707,516
72,707,562
Using an unique_ptr as a member of a struct
So I have a struct like this: struct node { node_type type; StaticTokensContainer token_sc; std::unique_ptr<node> left; // here std::unique_ptr<node> right; // and here }; When I tried to write a recursive function to convert a node to string for printing like this: std::string node_to_string(node n) { return "<other members converted to strings>" + node_to_string(*(n.left)); } It gives me: function "node::node(const node &)" (declared implicitly) cannot be referenced -- it is a deleted function I don't understand why this error is showing up, I had no problem when I did (*n) when I tried passing n as std::unique_ptr<node>, so I don't see why doing *(n.left) is not allowed.
you pass node by value, and you cannot set one std::unique_ptr equal to another: int main() { std::unique_ptr<node> a = std::make_unique<node>(); std::unique_ptr<node> b = a; //Error C2280 } because who is now the unique owner of the data? To fix your error, simple take a const reference in your function. This way, you pass the reference and that won't create copies: std::string node_to_string(const node& n) { return "<other members converted to strings>" + node_to_string(*(n.left)); } (you should also think about exiting this function, otherwise you will get either get a stack overflow or a dereferenced nullptr, whichever comes first. For example, add if (!n.left) return "";)
72,708,798
72,709,956
shrink and grow an object using cos and time in vertex shader
so here is my problem. I have to make a rabbit grow and shrink using a time variable and a cos() I managed to pass the time variable to my vertex shader but I have absolutely no idea how to make the rabbit grow or shrink. I try some formula that I find on the internet but none works I will show the code where I pass my variable time to the vertex shader as well as my vertex shader. sorry english is not my first language my animate function : void MaterialTP2::animate(Node* o, const float elapsedTime) { Camera * test = Scene::getInstance()->camera(); glProgramUniformMatrix4fv(m_ProgramPipeline->getId(), l_View, 1, GL_FALSE, glm::value_ptr(test->getViewMatrix())); glProgramUniformMatrix4fv(m_ProgramPipeline->getId(), l_Model, 1, GL_FALSE, glm::value_ptr(o->frame()->getModelMatrix())); glProgramUniformMatrix4fv(m_ProgramPipeline->getId(), l_Proj, 1, GL_FALSE, glm::value_ptr(test->getProjectionMatrix())); glProgramUniform1f(m_ProgramPipeline->getId(), glGetUniformLocation(vp->getId(), "time"), elapsedTime); } here is my vertex shader : #version 460 #define PI 3.1415926538 uniform mat4 Model; uniform mat4 View; uniform mat4 Proj; uniform float time; out gl_PerVertex { vec4 gl_Position; float gl_PointSize; float gl_ClipDistance[]; }; layout (location = 0) in vec3 Position; layout(location = 2) in vec3 normal; varying vec3 out_color; void main() { float scaleFactor = 0.2 * cos((2 * PI) / time * 100 ); gl_Position = Proj * View * Model * vec4(Position ,1.0) ; out_color = 0.5 * normal + vec3(0.5, 0.5, 0.5); } the rabbit
You have to scale the vertex coordinate: float scaleFactor = 0.2 * (cos((2 * PI) / time * 100) + 2.0); gl_Position = Proj * View * Model * vec4(Position * scaleFactor, 1.0); However, I suggest to scale the model transformation matrix on the CPU: glm::mat4 modelMatrix = glm::scale(o->frame()->getModelMatrix(), glm::vec3(scaleFactor)); glProgramUniformMatrix4fv(m_ProgramPipeline->getId(), l_Model, 1, GL_FALSE, glm::value_ptr(modelMatrix));
72,709,043
72,709,119
Dynamic macro-selection in a loop
I have a header file 'a.h' with some macro-definitions of the type: Header 'a.h' contents: #define STREAM1 cout #define STREAM2 cerr #define STREAM3 some_out_stream3 #define STREAM4 some_out_stream4 ... #define STREAM100 some_out_stream100 Now in a different c file which includes the above header, I need to use the above macros, in the following way. STREAM1 << some_text_method( 1 ); STREAM2 << some_text_method( 2 ); ... STREAM100 << some_text_method( 100 ); Is there a way, possibly by macro or function definition, to do the above in a loop: int i; for(i = 1; i <= 100; i++) SOME_MACRO_OR_METHOD( i );
Put all the macros in an array and loop over them. std::ostream streams[] = {STREAM1, STREAM2, ...STREAM100}; for (int i = 0; i < std::size(streams); i++) { streams[i] << some_text_method(i+1); }
72,709,133
72,709,178
__declspec(align(#)) equivalent with i686-w64-mingw32-g++ compiler
Hello I'm doing a MASM course and there is also C++ but the teacher is using Visual Studio and I'm using Linux. In the code I'm doing there is the following instructions: __declspec(align(#)) I have this code: _desclspec(align(16))XmmVal a; _desclspec(align(16))XmmVal b; _desclspec(align(16))XmmVal c[2]; But I cannot use "align" and "_desclspec" on linux by compiling with "i686-w64-mingw32-g++" because I get an error "was not declared in this scope": SSEPackedIntegerArithmetic.cpp:24:16: error: ‘align’ was not declared in this scope 24 | _desclspec(align(16))XmmVal a; | ^~~~~ SSEPackedIntegerArithmetic.cpp:24:5: error: ‘_desclspec’ was not declared in this scope 24 | _desclspec(align(16))XmmVal a; | ^~~~~~~~~~ How can I solve this problem? Thank you!
The issue isn't "Windows vs. Linux" as much as "choice of compiler". Here's the documentation for MSVC. Note the caveat about "MSVS 2015 and later": https://learn.microsoft.com/en-us/cpp/cpp/align-cpp In Visual Studio 2015 and later, use the C++11 standard alignas specifier to control alignment. For more information, see Alignment. The equivalent to _declspec(align(16)) for gcc would be: https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html __attribute__((aligned (16))) You should definitely see if your compiler supports alignas.
72,710,346
72,710,516
How to use std::format to format all derived class of the same base class?
I have lots of classes derived from the same base class, and I'm trying to avoid writing a formatter for all derived classes. I tried to only implement the std::formatter for the base class, but passing a derived class object/reference to std::format will trigger compile errors. C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.32.31326\include\format(1496): error C2665: 'std::_Format_arg_traits<_Context>::_Phony_basic_format_arg_constructor': none of the 5 overloads could convert all the argument types with [ _Context=std::format_context ] ... Minimal code is as follows: #include <format> #include <iostream> #include <string> using namespace std; struct Base { virtual string ToString() { return "Base"; } }; struct D1 : public Base { string ToString() override { return "D1"; } }; template <typename CharT> struct ::std::formatter<Base, CharT> : ::std::formatter<::std::string> { // parse is inherited from formatter<string>. template <typename FormatContext> auto format(Base &e, FormatContext &ctx) const { ::std::string name = e.ToString(); return ::std::formatter<::std::string>::format(name, ctx); } }; int main(int argc, char const *argv[]) { string s; D1 d; s = format("{}", d); // this triggers compile errors saying no overloads found cout << s << endl; Base &b = d; s = format("{}", b); // ok after explicit converting to base reference cout << s << endl; return 0; } I'm assuming that the compiler should automatically convert Derived& to Base&, but that doesn't happen. What's the correct way to achieve this?
Base and D1 are different types. A more appropriate way should be to use constrained templates #include <concepts> #include <format> template<std::derived_from<Base> Derived, typename CharT> struct std::formatter<Derived, CharT> : std::formatter<std::string> { template<typename FormatContext> auto format(Derived& e, FormatContext& ctx) const { std::string name = e.ToString(); return std::formatter<std::string>::format(name, ctx); } }; Demo
72,711,521
72,715,937
Win11 22H2 Programmatically switch between predefined power modes (Best power efficiency/Balanced/Best performance)
How do you programmatically switch between predefined power modes (Best power efficiency/Balanced/Best performance) in Win11 22H2? Is this still possible given that Microsoft is now removing all Sleep/Screen off overrides?
You can use Powercfg command-line options Setting the "Super performance" scheme active: powercfg /setactive ac093644-6503-4314-b3b6-0b601924e3e9 A detailed tutorial can be found here: https://www.windowscentral.com/how-use-powercfg-control-power-settings-windows-10 And of course, you can set all values in the registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Power\PowerSettings
72,711,708
72,721,031
How to pass wide characters to libcurl API which takes only const char*?
I'm using libcurl to upload some files to my server. I need to handle files whose names are in different languages e.g. Chinese, Hindi, etc. For that, I need to handle files using std::wstring instead of std::string. libcurl has a function with a prototype like below: CURLcode curl_mime_filename(curl_mimepart *part, const char *filename); But I cannot pass std::wstring::c_str() because it will return const wchar_t* instead of const char*. Edit: I still don't know what encoding scheme is used by the server as it is a third party app so I used std::wstring for handling filenames and the conversion from std::wstring to std::string is done by the below function I found on this forum. std::string ws2s(const std::wstring& wstr) { using convert_typeX = std::codecvt_utf8<wchar_t>; std::wstring_convert<convert_typeX, wchar_t> converterX; return converterX.to_bytes(wstr); }
curl_mime_filename is not suitable for files whose names are in different languages e.g. Chinese, Hindi, etc. It is suitable for ASCII and UTF-8 file name encodings only. The job of curl_mime_filename is: Detect the data content type, for example file.jpg → image/jpeg. Add the multipart header Content-Disposition, for example Content-Disposition: attachment; name="data"; filename="file.jpg". The encoding to filename= is not set. If you know the server encoding, then encode the chars 0x80 .. 0xff in filename to %80 .. %ff: Example for UTF8: Naïve file.txt → Na%C3%AFve%20file.txt. Example for UCS2: file.txt → %00f%00i%00l%00e%00.%00t%00x%00t. Pass the encoded file name to curl_mime_filename. If you do not know the server encoding used or whish to use another encoding, then do not use curl_mime_filename. Use the desired char encoding for the filename. Encode the chars over 0x7f like above. Use curl_mime_headers and set the headers mentioned above, use filename*= instead of filename=. struct curl_slist *headers = nullptr; headers = curl_slist_append(headers, "Content-Type: image/jpeg"); headers = curl_slist_append(headers, "Content-Disposition: attachment; name=\"data\"; filename*=UTF-8''Na%C3%AFve%20file.txt"); curl_mime_headers(part, headers, true);
72,711,720
72,725,085
Is there a way to show tool tips for QRubberBand?
I am trying to set a tool tip for QRubberBand. This is how the constructor of the parent looks. Please note the parent is not a window, but rather a widget of a window. roiRB = new QRubberBand( QRubberBand::Rectangle,this); roiRB->setGeometry(QRect(QPoint(1,1), QPoint(100,100))); roiRB->setAttribute(Qt::WA_AlwaysShowToolTips); //I tried this line as mentioned in the Documentation to all parent classes of the QRubberBand. roiRB->setToolTip("Hello"); roiRB->setToolTipDuration(1000); However the tooltip is not popping, I tried different values for toolTipDuration as well.
On digging the source code of QRubberBand, I found out that in the constructor of QRubberBand, the attribute (Qt::WA_TransparentForMouseEvents); is set to true. Manually setting this back to false fixed the issue. From what I see, tooltips work on MouseEvent calls of the widget, if the this attribute is set to true, the widget ignores MouseEvents and thereby nullifying the setToolTip("abcd"). Therefore, roiRB = new QRubberBand( QRubberBand::Rectangle,this); roiRB->setAttribute(Qt::WA_TransparentForMouseEvents,0); is all you need to do. Do let me know if I have missed something.
72,712,115
72,712,883
std::chrono::system_clock::now() serialization
How can I serialize the result of std::chrono::system_clock::now() so I can then load it and compare it with a later timestamp? I tried to serialize in the following way: std::to_string((uint64_t)std::chrono::system_clock::now().time_since_epoch().count()) Then to unserialize it: std::chrono::milliseconds t(<uint64 number>); std::chrono::time_point<std::chrono::system_clock>(t); The deserialization is not working, the object is the first day of 1970 Minmum example: #include <iostream> #include <chrono> using namespace std; static std::string clockToStr(std::chrono::system_clock::time_point timestamp) { static char buffer[64]; std::time_t t = std::chrono::system_clock::to_time_t(timestamp); ::ctime_r(&t, buffer); return std::string(buffer); } int main() { uint64_t t1 = std::chrono::system_clock::now().time_since_epoch().count(); std::chrono::milliseconds t(t1); auto t2 = std::chrono::time_point<std::chrono::system_clock>(t); std::cout<<clockToStr(t2)<<std::endl; return 0; }
As noted, time_since_epoch is not necessarily in milliseconds. If you want to serialize milliseconds, use duration_cast. Otherwise something like this should work: using clock_t = std::chrono::system_clock; clock_t::time_point tp = clock_t::now(); std::string serialized = std::to_string(tp.time_since_epoch().count()); clock_t::time_point tp1(clock_t::duration(std::stoll(serialized))); We use the time_point constructor that uses a duration, which is the opposite of the time_since_epoch() method. The serialization is a bit wonky because I use long long. Better would be something that detects the type of clock_t::duration::rep. Something like this: std::ostringstream os; os << tp.time_since_epoch().count(); std::string serialized = os.str(); std::istringstream is(serialized); clock_t::rep count; is >> count; clock_t::time_point tp1{clock_t::duration{count}};
72,712,318
72,713,395
converting to ‘A’ from initializer list would use explicit constructor ‘A::A(int)’
I am trying to migrate an old C++03 codebase to C++11. But I fail to understand what gcc is warning me about in the following case: % g++ -std=c++03 t.cxx % g++ -std=c++11 t.cxx t.cxx: In function ‘int main()’: t.cxx:8:21: warning: converting to ‘A’ from initializer list would use explicit constructor ‘A::A(int)’ 8 | int main() { B b = {}; } | ^ t.cxx:8:21: note: in C++11 and above a default constructor can be explicit struct A { explicit A(int i = 42) {} }; struct B { A a; }; int main() { B b = {}; return 0; } All I am trying to do here is a basic zero initialization. It seems to be legal for C++03, but I fail to understand how to express the equivalent in C++11. For reference, I am using: % g++ --version g++ (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
The given program is ill-formed for the reason(s) explained below. C++20 B is an aggregate. Since you're not explicitly initializing a, dcl.init.aggr#5 applies: For a non-union aggregate, each element that is not an explicitly initialized element is initialized as follows: 5.2 Otherwise, if the element is not a reference, the element is copy-initialized from an empty initializer list ([dcl.init.list]). This means that a is copy initialized from an empty initializer list. In other word, it is as if we're writing: A a = {}; // not valid see reason below Note also that list-initialization in a copy initialization context is called copy-list-initialization which is the case here. And from over.match.list#1.2: In copy-list-initialization, if an explicit constructor is chosen, the initialization is ill-formed. Essentially, the reason for the failure is that A a = {}; is ill-formed. C++11 Since B is an aggregate and there are fewer initializer-clauses in the list than there are members in the aggregate, and from aggregate initialization documentation: The effects of aggregate initialization are: If the number of initializer clauses is less than the number of members and bases (since C++17) or initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default member initializers, if provided in the class definition, and otherwise (since C++14) copy-initialized from empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates). This again means that a is copy initialized from an empty list {}. That is, it is as if we're writing: A a = {}; // not valid see reason below But from over.match.funcs: In copy-list-initialization, if an explicit constructor is chosen, the initialization is ill-formed. So again we face the same problem i.e., A a = {}; is not valid. Solution To solve this, we can pass A{} or A{0} as the initializer inside the list as shown below: B b = { A{} }; //ok now B c = { A{0} }; //also ok Working demo. Note Note that writing A a{}; on the other hand is well-formed as this is a direct-initialization context and so it is direct-list-initialization.
72,712,405
72,712,584
C++: Is it possible to use a function of a class from outside?
Is there any way to use a class member function from outside? As far as I know for this it would be necessary to somehow inject a private component into it. For example (this is just an example the notFooClass function does not compile): class FooClass{ private: int i; public: FooClass(int x){ this->i = x; } int f(int num){ return i+num; } }; int notFooClass(int num1, int num2){ return FooClass(num1)::f(num2); // } int main(){ FooClass x(10); std::cout<<x.f(5)<<std::endl; std::cout<<notFooClass(10, 5)<<std::endl; return 0; The output should be: 15 15 Is it even possible to do something similar?
public methods can be called from outside. Thats what they are for. notFooClass creates an instance and calls a member function. Thats basically the same as you do in main. The difference is only that you are using an unnamed temporary and wrong syntax: int notFooClass(int num1, int num2){ return FooClass(num1).f(num2); } or with a named object to illustrate the similarity to main: int notFooClass(int num1, int num2){ FooClass x(num1); return x.f(num2); }
72,712,601
72,713,380
Templated requires clause fails
I have a set of classes roughly defined as follows: template <typename U> class Iterable { // More code }; class Container : public Iterable<Element> { // More code }; class Tuple : public Container { // More code }; class List { public: template <typename I, typename T> requires std::is_base_of_v<Iterable<T>,I> explicit List(const I& i) { for (const T& e : i) elems_.emplace_back(e,true); } // More code }; Trying to create a List from Tuple as Tuple t1(1,2,3); List l1(t1); gives the following complilation message /home/felix/git/libraries/cpp_script/tests/test_list.cpp:96:15: error: no matching function for call to ‘cs::List::List(cs::Tuple&)’ 96 | List l1(t1); | ^ In file included from /home/felix/git/libraries/cpp_script/tests/test_list.cpp:3: /home/felix/git/libraries/cpp_script/include/list.hpp:72:10: note: candidate: ‘template<class I, class T> requires is_base_of_v<cs::Iterable<T>, I> cs::List::List(const I&)’ 72 | explicit List(const I& i) { | ^~~~ /home/felix/git/libraries/cpp_script/include/list.hpp:72:10: note: template argument deduction/substitution failed: /home/felix/git/libraries/cpp_script/tests/test_list.cpp:96:15: note: couldn’t deduce template parameter ‘T’ 96 | List l1(t1); | ^ I don't understand why the substitution fails. I==Tuple and T==Element should satisfy the require clause just fine.
Your example won't work because there is no way to deduce the type of T. If you want to constrain I to inherit from base class Iterable<U> for some type U, you might want to do template <typename U> class Iterable { }; template<typename T> concept derived_from_iterable = requires (T& x) { []<typename U>(Iterable<U>&){}(x); }; class List { public: template<derived_from_iterable I> explicit List(const I& i) { // More code } }; Demo
72,713,158
72,714,213
C++20 Constraints - Restrict typename TFunction to be a function (with certain signature)
How to translate this TS Code into modern C++20 using lambdas and modern templating features? [Edit]: The main question here is: How to restrict typename TFunction to be of type Function or even a more specific function with a given signuature? interface Subscription<TFunction extends Function> { readonly subscriber: TFunction; unsubscribe(); } class Subscriptions<TFunction extends Function = Function> { private _subscriptions: Subscription<TFunction>[] = []; subscribe(f: TFunction): Subscription<TFunction> { // ... const _subscription: Subscription<TFunction> = { subscriber: f, unsubscribe: () => { this._subscriptions = this._subscriptions.filter(s => s !== f); }; }; this._subscriptions = [...this._subscriptions, _subscription]; return _subscription; } }
Function types in C++ are expressed as types like R(Arg1, Arg2, Arg3) (denoting a function that takes three arguments of types Arg1, Arg2, Arg3 and returns an R). You can take a pointer to such a function, which has the type R(*)(Arg1, Arg2, Arg3). A template will typically use one type parameter for R and a parameter pack to generalise over all parameter types, e.g. template <typename R, typename... Args> /* something involving the type R(Args...) */ If you want to include objects with appropriate operator() (especially lambdas), you can use std::function<R(Args...)> to type erase the specific type of each subscriber. Something like template <typename Sig> struct Subscription { std::function<Sig> subscription; void unsubscribe(); }; template <typename R, typename... Args> class Subscriptions { std::vector<Subscription<R(Args...)>> subscriptions; public: R notify(Args... args) { R result; for (auto & s : subscriptions) result += s.subscription(args...); return result; } Subscription<R(Args...)> subscribe(std::function<R(Args...)> s); }; Because you have to be explicit about object lifetimes in C++, lambda captures are more complex, so the implementation of unsubscribe is going to be tricky, in particular std::function<Sig> is not equality comparable with itself.
72,713,652
72,713,872
Deduce Function Arguments From A Function Type Declare, For Templated Struct Method?
I was wondering if it was possible to deduce the return type, and parameters from a function type define. I was hoping to do something similar: template<class T> struct _function_wrapper_t { [return of T] call([Args of T]....) { return (T)m_pfnFunc(Args); } void* m_pfnFunc; }; int MultiplyTwoNumbers(int nNum, int nNum2) { return nNum * nNum2; } int MultiplyThreeNumbers(int nNum, int nNum2, int* pnNum3) { return nNum * nNum2 * *pnNum3; } int main() { _function_wrapper_t<decltype(&MultiplyTwoNumbers)> two(&MultiplyTwoNumbers); _function_wrapper_t<decltype(&MultiplyThreeNumbers)> three(&MultiplyThreeNumbers); auto ret1 = two.call(1, 2); auto ret2 = three.call(4, 5, 8); } However I'm not sure if its possible to discern the return type and function arguments from a type of function pointer. if you did say typedef void*(__cdecl* fnOurFunc_t)(const char*, int, float**); The compiler knows to use that as the type in the future, does the same apply further to templates? This is needed for a VERY specific use case. Thanks in advance!
The simple solution is to let the compiler deduce return type and let the caller pass the right types (and fail to compile when they don't): template<class T> struct _function_wrapper_t { template <typename ...U> auto call(U&&... t) { return m_pfnFunc(std::forward<U>(t)...); } T m_pfnFunc; }; If you do not like that you can use partial specialization: template<class T> struct _function_wrapper_t; template <typename R,typename...Args> struct _function_wrapper_t<R(*)(Args...)> { R call(Args...args) { return m_pfnFunc(args...); } using f_type = R(*)(Args...); f_type m_pfnFunc; }; Live Demo PS: perfect forwarding is also possible in the latter case but it requires some boilerplate that I left out for the sake of brevity.
72,713,796
72,722,468
Problem while linking a static library during compilation in MinGW, why?
I am trying to compile a simple project which uses one of my headers. I am on Windows and I am using MinGW-W64-builds-4.3.5 Suppose the project is called test.cpp and I want to compile it using my headerosmanip which requires also the linking of its created static library libosmanip.lib. The static library has been compiled and created in MSYS2 and then copied into Windows filesystem. If I try to compile with: g++ -std=c++17 -losmanip .\test.cpp To search for the system headers and library path I did: g++ -v test.cpp and decided to put headers into C:\MinGW\bin\..\lib\gcc\i686-w64-mingw32\8.1.0\include\c++ and the static library into C:\MinGW\lib\gcc\i686-w64-mingw32\8.1.0\. I got the following error: C:/MinGW/bin/../lib/gcc/i686-w64-mingw32/8.1.0/../../../../i686-w64-mingw32/bin/ld.exe: cannot find -losmanip collect2.exe: error: ld returned 1 exit status I've tried also by adding the -L option, linking the library path, or editing the LIBRARY_PATH variable ( $Env:LIBRARY_PATH+=";C:/MinGW/bin/../lib/gcc/i686-w64-mingw32/8.1.0/"), but it still doesn't work. I tried to move the library into the same folder of the test.cpp file and compile, but again the same error occurs. It's strange because I tried same thing on Ubuntu, MacOS, MSYS2 and Cygwin64 and it works. Can you help, me please?
I finally solved the issue. The problem was related to the fact the the suffix of my library was .lib. By changing it in .a and rebuilding the library passing the correct static library name to the ar command the problem disappeared.
72,713,971
72,728,392
In C++, how to correctly obtain a shared pointer to a vector , minimizing the number of copy constructor calling?
I need a function which returns a shared_ptr to a vector containing a large number of objects. The following code realizes this but one can see that copy constructors are called for an extra number of times. #include <iostream> #include <vector> #include <memory> using namespace std; class A { public: int IA ; A(int ia) { cout << "Constructor is called\n" ; IA = ia ; } A(const A& a) { cout << "Copy constructor is called\n" ; IA = a.IA ; } } ; shared_ptr<vector<A>> foo() { vector<A> myA ; myA.push_back(A(10)) ; myA.push_back(A(20)) ; return make_shared<vector<A>>(myA) ; } int main() { shared_ptr<vector<A>> myA ; myA = foo() ; return 0 ; } In real cases, A may also be bigger, so to make_shared<vector<A>>(myA) ; would cause unncessary copying process. I wonder if there is any way to reduce copy constructor calling times.
There are two usages in your code that cause extra copying. myA.push_back(A(10)) will create a temporary object of class A, which is then copied into the vector myA. Note that we cannot reduce such duplication by changing to myA.emplace_back(A(10)). It will also creates a temporary A object, and then calls the constructor of A with the temporary (xvalue) as an argument. This will call the copy constructor (since you didn't provide move constructor). make_shared<vector<A>>(myA) will create the managed object in std::shared_ptr from myA, which will be copied. Copying a vector will copy all of its elements. Solutions: Provide appropriate arugment to emplace_back. Here we can write myA.emplace_back(10). Now it will call the constructor of A with argument 10, which will select the constructor A(int). That is, construct the object of class A directly in the vector, instead of creating a temporary and then copying it into the vector. Move myA into the shared_ptr by make_shared<vector<A>>(std::move(myA)). Here it will not copy the elements in the vector. Note that as the capacity of the vector increases, its elements will also be copied. There are some solutions. If you know the number of elements, you can use reserve() to pre-allocate enough memory. You can also previde a noexcept move constructor for class A to avoid copying when changing the capacity.
72,714,020
72,714,365
C++ share atomic_int64_t between different process?
I am using C++ multi-processing passing data from one to another using shared memory. I put an array in the shared memory. Process A will copy data into the array, and Process B will use the data in the array. However, process B need to know how many item are in the array. Currently I am using pipe/message queue to pass the array size from A to B. But I thinks I might put an atomic variable(like atomic_uint64_t) in the shared memory, modify it in process A and load it in process B. However I have the following questions. Is Atomic variable in C++ still atomic between process? I know atomic is implemented locking the cache line, neither another thread nor process can modify the atomic variable. So I think the answer is Yes. How exactly should I shared a atomic variable between? Can any one give an example?
Atomics will work, for the most part. Some caveats: Only use lock-free atomics. See Are lock-free atomics address-free in practice? Obviously pointers won't work, for example std::atomic<std::shared_ptr<T>> std::atomic<T>::wait, and notify_one/all may not work Technically, the behavior is non-portable (and lock-free does not guarantee address-free) but basic use including acquire-release should work on all mainstream platforms. If you already have shared memory, the use should be pretty simple. Maybe something like this: struct SharedBuffer { std::atomic<std::size_t> filled; char buf[]; }; SharedBuffer* shared = static_cast<SharedBuffer*>( mmap(..., sizeof(SharedBuffer) + size, ...)); fill(shared->buf); shared->filled.store(size, std::memory_order_release); Note that you still have to solve the issue of notifying the other process. To the best of my knowledge, you cannot use std::condition variables and std::mutex. But the OS-specific types may work. For example for pthreads, you need to set pthread_mutexattr_setpshared and pthread_condattr_setpshared. Maximizing portability int64_t may be a bit risky if your CPU architecture is 32 bit and doesn't come with 64 bit atomics. You can check at runtime with atomic_is_lock_free or at compile time with is_always_lock_free. Similarly, size_t may be risky if you want to mix 32 bit and 64 bit binaries. Then again, when targeting mixed binaries, you have to limit yourself to less than 32 bit address space anyway. If you want to provide a fallback for missing lock-free atomics, atomic_flag is guaranteed to be lock-free. So you could roll your own spinlock. Personally, I wouldn't invest the time, however. You already use OS-facilities to set up shared memory. It is reasonable to make some assumptions about the runtime platform.
72,714,058
72,714,163
Does the stack implementation that's part of the C++ STL have a capacity?
I learned in my college DSA course that a stack is initialized with a capacity that limits the number of elements it can contain. But when I create a stack using the STL, you don't have to define a capacity. Is there a capacity involved, or does it not apply in the STL implementation? Do stacks even really need a capacity?
The stack implementation you looked at in your course may have had a limit, but that's not essential to being a stack. (And your course really should have taught you this.) The C++ standard library stack is just an adapter for any underlying collection that supports the necessary operations, so whether it has a limited capacity or not depends on that underlying type. (The default is std::deque.)
72,714,268
72,720,810
OMP reduction for loop with std::map
I want to parallelise the following for loop with a std::map with OpenMP 4.0: int n=5000; int nbin; std::map<int, int> histogram; for (int i = 1; i < n; i++) { . . nbin =....... \\some calculation with integer result ++histogram[nbin]; } I tried before the for loop: #pragma omp declare reduction( \ +:std::map<int, int> : \ omp_out += omp_in \ ) initializer(omp_priv = 0) #pragma omp parallel for reduction(+ : histogram) But it gives the error: no viable conversion from 'int' to 'std::map<int, int>' How would be the correct reduction statement? thanks for help!
Ok, toy example counting characters in a string: string text{"the quick brown fox jumps over the lazy dog"}; charcounter<char,int> charcount; #pragma omp declare reduction\ ( \ +:charcounter<char,int>:omp_out += omp_in \ ) \ initializer( omp_priv = charcounter<char,int>{} ) #pragma omp parallel for reduction(+ : charcount) for ( int i=0; i<text.size(); i++ ) { char c = text[i]; charcount.inc(c); } (I think I can probably make that inc function look more like your ++foo[k], but that's for later.) Implementation of the charcounter class, which is basically a map: template<typename key,typename value> class charcounter : public map<key,value> { public: void operator+=( const charcounter<key,value>& other ) { for ( auto [k,v] : other ) if ( this->contains(k) ) this->at(k) += v; else this->insert( {k,v} ); }; void inc(char k) { if ( this->contains(k) ) this->at(k) += 1; else this->insert( {k,1} ); }; }; Note that this only demonstrates that it is possible to do a reduction on a map. Performance may dictate you using a totally different solution.
72,714,516
72,714,983
Call function in C++ dll from C#
I'm trying to call a function in a C++ dll, from C# code. The C++ function : #ifdef NT2000 __declspec(dllexport) #endif void MyFunction ( long *Code, long Number, unsigned char *Reference, unsigned char *Result ) ; And my C# call is : [DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void MyFunction(ref IntPtr Code, int Number, string Reference, ref IntPtr Result); This function is supposed to return "Code" and "Result" The "Code" value that I get seems to be ok, but "Result" seems not ok, so I'm wondering if I'm getting the string value that I expect or the memory address ? Thanks for your help.
long in C maps to int in C#. And char is ANSI, so you need to specify UnmanagedType.LPStr. The Result appears to be an out parameter, for which you will need to pre-assign a buffer (size unknown?) and pass it as StringBuilder [DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void MyFunction( ref int Code, int Number, [MarshalAs(UnmanagedType.LPStr)] string Reference, [MarshalAs(UnmanagedType.LPStr), Out] StringBuilder Result); Use it like this var buffer = new StringBuilder(1024); // or some other size MyFunction(ref myCode, myNumber, myReference, buffer);
72,714,763
72,714,938
Array changes it's values inside a function but other variable don't
#include <iostream> using std::cout; using std::cin; using std::endl; void func(int arr[5], int n1, int n2) { cout << "INSIDE func()" << endl; arr[0]++, arr[3]++; for(int i = 0; i < 5; i++) { cout << arr[i] << ' '; } cout << endl; n1++, n2++; cout << n1 << ' ' << n2 << endl; } int main() { int a = 3, b = 4; int arr[5] = {0,0,0,0,0}; func(arr,a,b); cout << "INSIDE main()" << endl; for(int i = 0; i < 5; i++) { cout << arr[i] << ' '; } cout << endl; cout << a << ' ' << b << endl; return(0); } So, why does arr[5] changes it's values in func() function, but variables a,b don't. Why does that happen? I know that to a,b change it's values i have to pass the reference of variables a , b to function func(). F.e: fill(int arr[5], int &n1, int &n2) { /* code */ } But why don't we pass arrays to functions in the same way? OUTPUT: INSIDE func() 1 0 0 1 0 4 5 INSIDE main() 1 0 0 1 0 3 4
This function declaration void func(int arr[5], int n1, int n2); is adjusted by the compiler to the declaration void func(int *arr, int n1, int n2); That is parameters having array types are adjusted by the compiler to pointers to array element types. On the other hand, this call func(arr,a,b); is equivalent to the call func( &arr[0], a, b ); That is the array designator arr used as the function argument is implicitly converted to a pointer to its first element. So in fact elements of the array are passed to the function through a pointer to them because using the pointer arithmetic and dereferencing pointer expressions the function has a direct access to elements of the array. For example these expressions arr[0]++, arr[3]++; by the definition are equivalent to ( *( arr + 0 ) )++, ( *( arr + 3 ) )++; As for the variables a and b then the function deals with copies of the values of these variables. If you want to get the same effect as with elements of the array you should define the function like void func(int arr[5], int *n1, int *n2) { cout << "INSIDE func()" << endl; arr[0]++, arr[3]++; for(int i = 0; i < 5; i++) { cout << arr[i] << ' '; } cout << endl; ( *n1 )++, ( *n2 )++; cout << *n1 << ' ' << *n2 << endl; } and call it like func( arr, &a, &b );
72,715,323
72,716,577
Output not matching the expected output for almost palindrome program in C++
I can't find any error in my code for an almost palindrome. The statement 'r = isPalindrome(str, p[0], p[1]-1);' is not getting executed while the function calls for p&q are getting executed fine. It prints values of only p & q. Can someone please explain what is wrong with the flow of the program? #include <iostream> #include<vector> using namespace std; int arr[2]; int* isPalindrome(string &s, int i, int j){ int sz = s.length(); if(i==j) return NULL; while(i<j){ if(s[i] == s[j]){ i++; j--; } else{ arr[0] = i; arr[1] = j; return arr; } } return NULL; } int main() { string s = "abcdefdba", str; int *p, *q, *r; // removes any additional character or spaces and make lower-case for(int i=0; i<s.length();i++){ if(s[i] >= 65 && s[i]<=90) str.push_back(s[i]+32); if((s[i] >=97 && s[i]<=122) || (s[i]>=48 && s[i]<=57)) str.push_back(s[i]); } p = isPalindrome(str, 0, str.length()-1); cout<<"pointer p: "<<p[0]<<p[1]<<endl; if(p==NULL) cout<<"true"; else{ q = isPalindrome(str, p[0]+1, p[1]); r = isPalindrome(str, p[0], p[1]-1); // not getting executed } cout<<"pointer q: "<<q[0]<<q[1]<<endl; cout<<"pointer r: "<<r[0]<<r[1]<<endl; if(q==NULL || r==NULL) cout<<"true"; else cout<<"false"; return 0; }
Lets assume you are right and the function isn't execute and lets find out why the compiler might optimize it in such a way that the function call is not needed: int* isPalindrome(string &s, int i, int j) returns a pointer to the global array arr or NULL and other than writing to arr it has no side effect. Lets analyze the main function then: p = isPalindrome(str, 0, str.length()-1); cout<<"pointer p: "<<p[0]<<p[1]<<endl; if(p==NULL) cout<<"true"; else { You dereferrence p so p must not be NULL, the compiler can always take the else branch. q = isPalindrome(str, p[0]+1, p[1]); r = isPalindrome(str, p[0], p[1]-1); // not getting executed } cout<<"pointer q: "<<q[0]<<q[1]<<endl; cout<<"pointer r: "<<r[0]<<r[1]<<endl; if(q==NULL || r==NULL) cout<<"true"; else cout<<"false"; Again you dereferrence q and r so they can not be NULL. So isPalindrom must have returned the address of arr in both cases and must have written arr[0] and arr[1], which is p, q and r. The second isPalindrom call changes p[0] and p[1] and that changes what the thrid isPalindrom call does. I don't think any of them can be skipped. But the compiler can potentially compute it all at compile time and eliminate it all. In the output you should see that the last two cout calls print the same thing. Maybe that makes you think one of the function calls is skipped. But what you see is that they both just print the same global arr. What you should do is return std::optional<std::pair<int, int>> instead of the global array. Better: int is not the right type of an index, that should be std::size_t. So std::optional<std::pair<std::size_t, std::size_t>> Why not return iterators of the substring instead? And make it const, the argument should be a const std::string &: std::optional<std::pair<std::string::const_iterator, std::string::const_iterator>> Or lets get really modern and return a string view: std::optional<std::string_view>
72,715,968
72,716,182
std::move with polymorphic move assignment operator and memory safety
I was wondering if the following code was safe, considering the child object is implicitly converted to type Parent and then moved from memory. In other words, when passing other to Parent::operator=(Parent&&) from Child::operator(Child&&), is the entire object "moved" with the parent call, or just the underlying Parent object? class Parent { public: // Constructors Parent& operator=(Parent&& other) noexcept { if (this == &other) return *this; str1_ = std::move(other.str1_); str2_ = std::move(other.str2_); return *this; } protected: std::string str1_, str2_; }; class Child : public Parent { public: // Constructors Child& operator=(Child&& other) noexcept { if (this == &other) return *this; // Are the following 2 lines memory safe? Parent::operator=(std::move(other)); str3_ = std::move(other.str3_); return *this; } private: std::string str3_; };
What you are doing is safe. You are just passing a reference to the base-class subobject to the base assignment operator. std::move doesn't move anything. It just makes an xvalue out of an lvalue, so that a rvalue reference may bind to it. The binding here is to a subobject because Parent is a base class type of Child. In fact you are exactly replicating the behavior that a defaulted move assignment operator would have (except that it wouldn't check for self-assignment, which is pointless if you are only forwarding to other assignment operators), which begs the question why you are defining it at all? Just follow the rule-of-zero and don't declare a move assignment operator. This goes for both Parent's and Child's move assignment operator.
72,715,987
72,727,895
creating UML or class diagram manually from existing project
Is there anyway to build manually a class or UML diagram from some part of existing code in Visual Studio Professional? Assume there are plenty of project and classes. Can i manually select some of the classes (with only some of its base/derived classes and member functions) I am interested in, and they are automatically transferred to boxes with arrows and so on...? The trivial and slow solution is to draw some boxes and corresponding arrows and then write the name of classes or member functions into boxes (With some drawing programs like Dia). However, can it be done maybe using a more efficient way with any plugin or extension? Because, my final aim is to make my own documentation (visually) from the code i am working at. The code is big and I want to develope my own documentation only on some selective parts during the next years...
You can install the Class Designer component. In addition, UML Designers have been removed.
72,716,773
72,717,230
eigen bind matrix row/column to vector l-value reference
How can i pass a column (or row) of a Matrix to a function as an l-value Vector reference? Here is an example for dynamically allocated matrices: #include "eigen3/Eigen/Eigen" void f2(Eigen::VectorXd &v) { v(0) = 0e0; } void f1(Eigen::MatrixXd &m) { if (m(0,0) == 0e0) { // both calls below fail to compile // f2(m.col(0)); // ERROR // f2(m(Eigen::all, 0)); //ERROR } return; } int main() { Eigen::MatrixXd m = Eigen::MatrixXd::Random(3,3); f1(m); return 0; } the call to f2 inside f1 triggers a compilation error, of type: error: cannot bind non-const lvalue reference of type ‘Eigen::VectorXd&’ {aka ‘Eigen::Matrix<double, -1, 1>&’} to an rvalue of type ‘Eigen::VectorXd’ {aka ‘Eigen::Matrix<double, -1, 1>’} I face the same issue with compile-time sized matrices, e.g. constexpr const int N = 3; void f2(Eigen::Matrix<double,N,1> &v) { v(0) = 0e0; } void f1(Eigen::Matrix<double,N,N> &m) { if (m(0,0) == 0e0) { // all calls below fail to compile // f2(m.col(0)); ERROR // f2(m(Eigen::all, 0)); ERROR // f2(m.block<N,1>(0,0)); ERROR } return; } int main() { Eigen::Matrix<double,N,N> m = Eigen::Matrix<double,N,N>::Random(); f1(m); return 0; }
This is what Eigen::Ref is designed to do. void f2(Eigen::Ref<Eigen::VectorXd> v) { v[0] = 123.; } void f1(Eigen::Ref<Eigen::MatrixXd> m) { m(1, 0) = 245.; } int main() { Eigen::MatrixXd m(10, 10); f1(m); f2(m.col(0)); assert(m(0,0) == 123.); assert(m(1,0) == 245.); // also works with parts of a matrix, or segments of a vector f1(m.bottomRightCorner(4, 4)); } Note that mutable references only work if elements along the inner dimension are consecutive. So it works with a single column of a column-major matrix (the default) but not a row. For row-major matrices it is vice-versa. const refs (const Eigen::Ref<const Eigen::VectorXd>&) do work in these cases but they create a temporary copy.
72,717,084
72,718,543
Pushing non dynamically allocated objects to a vector of pointers
I've been trying to figure out this issue while I was coding on Codeblocks but didn't have any luck. So basically I have the following code inside a function: Node * newNode; newNode->data = num; //root is defined somwhere at the top as 'Node * root'; root->adj.push_back(newNode); and the following struct: struct Node{ int data; vector<Node*> adj; }; When I do the push_back to the vector the program just cycles for 2-3 seconds and exits with a non-zero exit code. If I allocate the memory dynamically It seems to work correctly. Does the program somehow blow up when the pointer is not pointing to a specific block of memory?
"Traversing" pointers that are not pointing at objects is undefined behavior in C++. The pointer doesn't have to point at a dynamically allocated object, but that is typical. The pointer could point at an automatic storage object. For example: Node bob; Node* root = &bob; however, in every case, you are responsible for managing lifetime of these objects. Automatic storage objects survive until the end of the current scope, temporary objects until the end of the current full expression, and dynamically allocated objects until they are deleted. Smart pointers can help a bit with lifetime management issues, but they only help. They do not solve it, and you still have to be aware of lifetime. Many post-C++ languages have automatic garbage collection that makes lifetime less of the programmers problem. You do not have this help in C++.
72,717,228
72,718,637
C++ std features and Binary size
I was told recently in a job interview their project works on building the smallest size binary for their application (runs embedded) so I would not be able to use things such as templating or smart pointers as these would increase the binary size, they generally seemed to imply using things from std would be generally a no go (not all cases). After the interview, I tried to do research online about coding and what features from standard lib caused large binary sizes and I could find basically nothing in regards to this. Is there a way to quantify using certain features and the size impact they would have (without needing to code 100 smart pointers in a code base vs self managed for example).
This question probably deserves more attention than it’s likely to get, especially for people trying to pursue a career in embedded systems. So far the discussion has gone about the way that I would expect, specifically a lot of conversation about the nuances of exactly how and when a project built with C++ might be more bloated than one written in plain C or a restricted C++ subset. This is also why you can’t find a definitive answer from a good old fashioned google search. Because if you just ask the question “is C++ more bloated than X?”, the answer is always going to be “it depends.” So let me approach this from a slightly different angle. I’ve both worked for, and interviewed at companies that enforced these kinds of restrictions, I’ve even voluntarily enforced them myself. It really comes down to this. When you’re running an engineering organization with more than one person with plans to keep hiring, it is wildly impractical to assume everyone on your team is going to fully understand the implications of using every feature of a language. Coding standards and language restrictions serve as a cheap way to prevent people from doing “bad things” without knowing they’re doing “bad things”. How you define a “bad thing” is then also context specific. On a desktop platform, using lots of code space isn’t really a “bad” enough thing to rigorously enforce. On a tiny embedded system, it probably is. C++ by design makes it very easy for an engineer to generate lots of code without having to type it out explicitly. I think that statement is pretty self-evident, it’s the whole point of meta-programming, and I doubt anyone would challenge it, in fact it’s one of the strengths of the language. So then coming back to the organizational challenges, if your primary optimization variable is code space, you probably don’t want to allow people to use features that make it trivial to generate code that isn’t obvious. Some people will use that feature responsibly and some people won’t, but you have to standardize around the least common denominator. A C compiler is very simple. Yes you can write bloated code with it, but if you do, it will probably be pretty obvious from looking at it.