question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
73,090,536
73,090,845
~__nat() deleted error in ThreadPool implementation
I am trying to implement a ThreadPool,but the clang compiler is giving me an error, which I do not know how to fix. My ThreadPool consists of 1 thread for planning and adding tasks to the queue (Scheduler), 1 thread for taking the tasks out of the queue and assigning separate threads to them(Executor), and child threads for each task. The problem arises in the Executor section: struct Executor { std::shared_ptr<SharedData> data_ptr_; // constructor explicit Executor (std::shared_ptr<SharedData>& data_ptr): data_ptr_ (data_ptr) {} // methods void execute () { while (true) { auto cur_task = data_ptr_ -> queue_.Take(); if (cur_task == std::nullopt) break; std::thread child_thread {&Executor::executeChild, this, std::move(cur_task)}; // ... } // join child threads here } void executeChild (Task task) { // ... task(); // ... } }; The compiler does not like this line: std::thread child_thread {&Executor::executeChild, this, std::move(cur_task)}; The error message that it produces is incomprehensible to me :( In template: attempt to use a deleted function error occurred here in instantiation of function template specialization 'std::__thread_execute<std::unique_ptr<std::__thread_struct>, void (tp::Executor::*)(fu2::detail::function<fu2::detail::config<true, false, fu2::capacity_default>, fu2::detail::proper... in instantiation of function template specialization 'std::__thread_proxy<std::tuple<std::unique_ptr<std::__thread_struct>, void (tp::Executor::*)(fu2::detail::function<fu2::detail::config<true, false, fu2::capacity_default>, fu2::detai... in instantiation of function template specialization 'std::thread::thread<void (tp::Executor::*)(fu2::detail::function<fu2::detail::config<true, false, fu2::capacity_default>, fu2::detail::property<true, false, void ()>>), tp::Executor ... '~__nat' has been explicitly marked deleted here Are there any errors in my code? What is the compiler saying?
The issue that cur_task is a std::optional<Task> and you pass this std::optional<Task> directly to executeChild(). But executeChild() expects not a std::optional<Task> but a Task. Since you check if the optional is nullopt before creating the thread, you probably want to use std::thread child_thread {&Executor::executeChild, this, std::move(*cur_task)}; The * in front of cur_task is operator*, which assumes that the optional contains a value and returns a reference to the contained value (if it doesn't, you have undefined behavior). Note there is also std::optional::value() which throws if the optional is empty. Reproducible example: The following code was adapted from your code, and shows the '~__nat' has been explicitly marked deleted here error with clang 14 and libc++ (example on godbolt) #include <memory> #include <thread> #include <optional> struct Task{ void operator()(){} }; struct SharedData{ std::optional<Task> Take() { return {}; } }; struct Executor { std::shared_ptr<SharedData> data_ptr_; // constructor explicit Executor (std::shared_ptr<SharedData>& data_ptr): data_ptr_ (data_ptr) {} // methods void execute () { while (true) { auto cur_task = data_ptr_ -> Take(); if (cur_task == std::nullopt) break; // Mistake in the following line: Need to use *cur_task std::thread child_thread {&Executor::executeChild, this, std::move(cur_task)}; // ... } // join child threads here } void executeChild (Task task) { // ... task(); // ... } }; Error: In file included from <source>:2: /opt/compiler-explorer/clang-14.0.0/bin/../include/c++/v1/thread:282:5: error: attempt to use a deleted function _VSTD::__invoke(_VSTD::move(_VSTD::get<1>(__t)), _VSTD::move(_VSTD::get<_Indices>(__t))...); ^ /opt/compiler-explorer/clang-14.0.0/bin/../include/c++/v1/__config:826:15: note: expanded from macro '_VSTD' #define _VSTD std ^ /opt/compiler-explorer/clang-14.0.0/bin/../include/c++/v1/thread:293:12: note: in instantiation of function template specialization 'std::__thread_execute<std::unique_ptr<std::__thread_struct>, void (Executor::*)(Task), Executor *, std::optional<Task>, 2UL, 3UL>' requested here _VSTD::__thread_execute(*__p.get(), _Index()); ^ /opt/compiler-explorer/clang-14.0.0/bin/../include/c++/v1/thread:309:54: note: in instantiation of function template specialization 'std::__thread_proxy<std::tuple<std::unique_ptr<std::__thread_struct>, void (Executor::*)(Task), Executor *, std::optional<Task>>>' requested here int __ec = _VSTD::__libcpp_thread_create(&__t_, &__thread_proxy<_Gp>, __p.get()); ^ <source>:26:21: note: in instantiation of function template specialization 'std::thread::thread<void (Executor::*)(Task), Executor *, std::optional<Task>, void>' requested here std::thread child_thread {&Executor::executeChild, this, std::move(cur_task)}; ^ /opt/compiler-explorer/clang-14.0.0/bin/../include/c++/v1/type_traits:1885:5: note: '~__nat' has been explicitly marked deleted here ~__nat() = delete; ^ 1 error generated. Compiler returned: 1 So clang with libc++ does not really provide a helpful error message, but neither does clang with stdlibc++ nor gcc nor MSVC.
73,091,092
73,091,330
How does the time function know the current time of the PC? Does it use the Internet to sync with a time server as the computers do?
How does the time function know the current time of the PC? I know how computers know the time. But how does the C++ time function implemented? Does it use the Internet to sync with a time server as the computers do? Or does it use the internal clock of the computer?
The function returns the current calendar time, which the program got by asking the computer what the current time is. The function doesn't require internet, just your computer's internal clock :) If you want to learn more on this topic, I highly recommend reading Programiz's C-Time.
73,091,534
73,091,605
How do I split a record of text into text file in C++
So I'm working on a simple file manipulating project where I need to append a new text on a single line, so, to visualize that suppose I have a text file called main.txt and in that file it contains a row of text that looks like this: [AB] 1 2 Now that lets say I want to add another text: [CB] & 4,5, then I want the updated file to looked like this: [AB] [CB] 1 4 2 5 But turns out it looked like this instead: [Ab] 1 2 [CB] 4 5 Here's what I've tried so far #include <iostream> #include <stdio.h> #include <fstream> #include <string> int main() { std::ofstream file("C:\users\USER\Documents\CPPPRoject\nice.txt",std::ios::out|std::ios::app); file << "\t" << "[CB]" << "\n"; file << "\t" << 4 << "\n"; file << "\t" << 5 << "\n"; return 0; }
#include <iostream> #include <fstream> using namespace std; int main() { // we have only 1 column in this example and also we have only 2 rows of data int columnCount = 1, dataRows = 2; string newColumnName; int data1, data2; cout << "enter the column name: "; cin >> newColumnName; // getting the new datas based on the amount of the rows int *data = new int[dataRows]; for (int i = 0; i < dataRows; i++) cin >> data[i]; // opening the orginal.txt and pasting it into copy.txt with new data fstream original, copy; original.open("original.txt", ios::in); copy.open("copy.txt", ios::out); // copy & paste the columns string inStr; for (int i = 0; i < columnCount; i++) { original >> inStr; copy << inStr << " "; } copy << newColumnName << "\n"; // copy past the columns int inData; for (int i = 0; i < dataRows; i++) { for (int j = 0; j < columnCount; j++) { original >> inData; copy << inData << " "; } copy << data[i] << "\n"; } original.close(); copy.close(); // deleting the original and renaming the copy.txt remove("original.txt"); rename("copy.txt", "original.txt"); return 0; } this is a simple code to add a column to the text file which only have 1 column of data , for doing it to larger file you can adjust columnCount and dataRows . sample test of code : original.txt before running the code [AB] 5 6 program inputs ( column name and new data to insert) enter the column name: [CD] 1 2 original.txt file after execution of the code [AB] [CD] 5 1 6 2
73,091,752
73,091,984
How can I get the return of a function called from a vector std::vector that contains std::function
I have a structure that in its constructor receives an initialization list std::initializer_list<P...> of type parameter pack. That constructor is filled with lambda functions, and they are saved in a std::vector<P...>. How can I get the return of those functions when traversing the vector calling each function? Here is an example of the structure and what I want to do: #include <iostream> #include <functional> #include <initializer_list> using namespace std; struct my_type { my_type(){} my_type(string _value) : value(_value) {} string value = "test"; string getValue(){return value;} }; template<typename A, class...P> struct struct_name { struct_name(std::initializer_list<P...> list) : functions(list) {} std::vector<P...> functions; string value; my_type type; string execute_functions(){ for (size_t i = 0; i < functions.size(); i++) { value = functions[i](type); // something like this, this does not work } return value; std::cout << value; } }; typedef struct_name<std::function<void(my_type)>, std::function<void(my_type)>> _functions; int main(int argc, char const *argv[]) { _functions object = { [](my_type var)->string{ return var.getValue(); }, [](my_type var)->string{ return var.getValue(); }, }; return 0; } Everything works perfect except the way to obtain those values. I don't know how, and no matter how hard I look I can't find answers. EDIT: I can't paste the complete code, because it depends on many other classes. I tried to recreate that section, the type is a parameter pack because it receives multiple types besides lambdas, but in the example I just put it that way.
You should be using std::tuple, if you want to store arbitrary callable objects. You can combine std::index_sequence with a fold expression for calling the functions: #include <iostream> #include <string> #include <tuple> #include <utility> using std::string; struct my_type { my_type(){} my_type(string _value) : value(_value) {} string value = "test"; string getValue(){return value;} }; template<class...P> struct struct_name { struct_name(P... args) : functions(args...) {} std::tuple<P...> functions; std::string value; my_type type; std::string execute_functions() { return execute_helper(std::make_index_sequence<sizeof...(P)>{}); } private: template<size_t ...Is> std::string execute_helper(std::index_sequence<Is...>) { ((value += std::get<Is>(functions)(type)), ...); return value; } }; int main() { struct_name foo( [](my_type var)->string { return var.getValue(); }, [](my_type var)->string { return var.getValue(); }); std::cout << foo.execute_functions() << '\n'; return 0; }
73,091,807
73,092,305
How can I write field value to a json file with boost?
I have some json file: { .... .... "frequency_ask": 900 } and need to change field frequency_ask to 1200 for example. I called my function void setFieldToJson(std::string json, std::string field, int value) { boost::property_tree::ptree pt; pt.put(field, value); std::ostringstream json; boost::property_tree::write_json(json, pt); } with next: setFieldToJson("../config_files/device.json", "frequency_ask", 1200); but doesn't work. How can I make it correct?
Your problem is most likely that you're using Property Tree, which is NOT a JSON library. Alternatively, it could be that your input is not valid JSON. Here's my take using Boost JSON: Live On Coliru #include <boost/json/src.hpp> // for header-only #include <fstream> void setFieldToJson(std::string const& filename, std::string field, int value) { std::string content; { std::ifstream ifs(filename, std::ios::binary); content.assign(std::istreambuf_iterator<char>(ifs), {}); } boost::json::parse_options opts; opts.allow_comments = true; opts.allow_invalid_utf8 = false; opts.allow_trailing_commas = true; auto doc = boost::json::parse(content, {}, opts); doc.at(field) = value; std::ofstream(filename, std::ios::binary) << doc; } int main(int argc, char** argv) { if (argc>1) { setFieldToJson( "device.json", "frequency_ask", std::stoi(argv[1])); } }
73,091,911
73,092,044
Compilation error on diamond problem(inheritance)
Why does the code below throw the following compilation error on msvc ? No default constructor exists for class 'Person' If I don't create a default constructor in the class Person, then should I delete the constructor of Employee and Student that takes only one argument and call Employee(name,age,grade) and Student(name,age,cl) from ctor of Manager although the Base class constructor is never going to get called from Employee and Student class? #include<iostream> #define endl '\n' using std::cout; class Person { std::string mname; int mage; public: //Person() = default; Person(const std::string& name, int age) :mname{ name }, mage{ age }{} }; class Employee :virtual public Person { int msalary; public: Employee(const std::string& name, int age, int sal) :Person{ name,age }, msalary{ sal }{} Employee(int sal): msalary { sal }{} }; class Student : virtual public Person { int mclass; public: Student(const std::string& name, int age, int cls) :Person{ name,age }, mclass{ cls }{} Student(int cls) :mclass{ cls } {} }; class Manager :public Student, Employee { private: public: Manager(const std::string& name,int age, int salary,int cl) :Person{name,age}, Student{cl}, Employee{salary} {} }; int main() { Manager manager{ "lorem",40,10000 ,10}; return 0; }
The cause of the problem: Both Employee and Student have constructors that do not call the only available constructor of the base class Person (requireing name and age parameters). Therefore the compiler will attempt to use a default constuctor fo the base class which is not available. You can handle it the following way: Decide what will be the default name and age for a Person derived class like Employee, Student. Use the defaults to construct the base, e.g.: static inline const std::string DEFAULT_NAME = "<default_name>"; static inline const int DEFAULT_AGE = 20; Employee(int sal) : Person(DEFAULT_NAME, DEFAULT_AGE), msalary{ sal } {}
73,091,965
73,092,716
Can somebody help me with EventHandling on WXWidgets
while trying to make some first progress with WXWidgets in C++ I´ve got on a problem. As youre able to see in the Code below, I´m trying to Handle an Button-Click-Event from an WXWidget-Application. The main Problem is that the dedicated Method TopPanel::OnClick() doesnt run. (Nothing is print to console) Possible Errors: Problem with my implementation of PanelEvents Wrongly installed WXWidgets (probably not cuz it does compile without any errors) #include <wx/wx.h> class App : public wxApp { public: virtual bool OnInit(); }; class MainFrame : public wxFrame { public: MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size); }; class TopPanel : public wxPanel { public: TopPanel(wxWindow* parent, wxSize size); private: void OnClick(wxCommandEvent &); wxDECLARE_EVENT_TABLE(); }; enum ButtonID { button_id_first = wxID_LAST + 1, button_id_other }; bool App::OnInit() { MainFrame* frame = new MainFrame("Nova Loader", wxDefaultPosition, wxDefaultSize); frame->Show(true); return true; } wxIMPLEMENT_APP(App); MainFrame::MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size) : wxFrame(nullptr, wxID_ANY, title, pos, size) { this->SetBackgroundColour(wxColor(25, 25, 25)); this->SetFocus(); TopPanel* pnl_top = new TopPanel(this, wxSize(500, 30)); wxPanel* pnl_bottom = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxSize(500, 270)); wxButton* btn_load = new wxButton(pnl_top, button_id_first, "Load"); wxButton* btn_exit = new wxButton(pnl_top, button_id_other, "Exit"); wxBoxSizer* s1 = new wxBoxSizer(wxVERTICAL); s1->Add(pnl_top, 0, wxALL, 5); s1->Add(pnl_bottom, 1, wxALL, 5); wxBoxSizer* s2 = new wxBoxSizer(wxHORIZONTAL); s2->Add(btn_load, 0, wxRIGHT, 5); s2->Add(btn_exit, 0); wxBoxSizer* s3 = new wxBoxSizer(wxVERTICAL); s3->Add(s2, 0, wxALIGN_RIGHT | wxRIGHT | wxTOP, 3); pnl_top->SetSizer(s3); pnl_bottom->SetBackgroundColour(wxColor(45, 45, 45)); this->SetSizerAndFit(s1); } TopPanel::TopPanel(wxWindow* parent, wxSize size) : wxPanel(parent, wxID_ANY, wxDefaultPosition, size) { this->SetSize(500, 30); this->SetId(wxID_ANY); this->SetBackgroundColour(wxColor(45, 45, 45)); } void TopPanel::OnClick(wxCommandEvent &e) { std::cout << e.GetId() << std::endl; } wxBEGIN_EVENT_TABLE(TopPanel, wxPanel) EVT_BUTTON(button_id_first, TopPanel::OnClick) EVT_BUTTON(button_id_other, TopPanel::OnClick) wxEND_EVENT_TABLE() Thanks to everyone trying to help me! ~ Tim
First things first, your given example successfully calls the OnClick method. So your claim that OnClick is not called is not correct. Now that being said, with newer(modern) wxWidgets you can also use dynamic event table using Bind instead of static event table as shown below. The changes made are highlighted as comments in the below given program: class TopPanel : public wxPanel { public: TopPanel(wxWindow* parent, wxSize size); void OnClick(wxCommandEvent &); //removed wxdeclare_event_table from here as no longer needed }; MainFrame::MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size) : wxFrame(nullptr, wxID_ANY, title, pos, size) { //other code as before //---------------------------------------------vvvvvvvv----------->let wxwidgets choose the id for you wxButton* btn_load = new wxButton(pnl_top, wxID_ANY, "Load"); //bind btn_load to onClick btn_load->Bind(wxEVT_BUTTON, &TopPanel::OnClick, pnl_top); //---------------------------------------------vvvvvvvv------------>let wxwidgets choose the id for you wxButton* btn_exit = new wxButton(pnl_top, wxID_ANY, "Exit"); //bind btn_exit to onclick btn_exit->Bind(wxEVT_BUTTON, &TopPanel::OnClick, pnl_top); //other code as before } Below is the complete working example that uses Bind: #include <wx/wx.h> class App : public wxApp { public: virtual bool OnInit(); }; class MainFrame : public wxFrame { public: MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size); }; class TopPanel : public wxPanel { public: TopPanel(wxWindow* parent, wxSize size); void OnClick(wxCommandEvent &); //removed wxdeclare_event_table from here as no longer needed }; enum ButtonID { button_id_first = wxID_LAST + 1, button_id_other }; bool App::OnInit() { MainFrame* frame = new MainFrame("Nova Loader", wxDefaultPosition, wxDefaultSize); frame->Show(true); return true; } wxIMPLEMENT_APP(App); MainFrame::MainFrame(const wxString& title, const wxPoint& pos, const wxSize& size) : wxFrame(nullptr, wxID_ANY, title, pos, size) { this->SetBackgroundColour(wxColor(25, 25, 25)); this->SetFocus(); TopPanel* pnl_top = new TopPanel(this, wxSize(500, 30)); wxPanel* pnl_bottom = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxSize(500, 270)); //---------------------------------------------vvvvvvvv----------->let wxwidgets choose the id for you wxButton* btn_load = new wxButton(pnl_top, wxID_ANY, "Load"); //bind btn_load to onClick btn_load->Bind(wxEVT_BUTTON, &TopPanel::OnClick, pnl_top); wxButton* btn_exit = new wxButton(pnl_top, wxID_ANY, "Exit"); //bind btn_exit to onclick btn_exit->Bind(wxEVT_BUTTON, &TopPanel::OnClick, pnl_top); wxBoxSizer* s1 = new wxBoxSizer(wxVERTICAL); s1->Add(pnl_top, 0, wxALL, 5); s1->Add(pnl_bottom, 1, wxALL, 5); wxBoxSizer* s2 = new wxBoxSizer(wxHORIZONTAL); s2->Add(btn_load, 0, wxRIGHT, 5); s2->Add(btn_exit, 0); wxBoxSizer* s3 = new wxBoxSizer(wxVERTICAL); s3->Add(s2, 0, wxALIGN_RIGHT | wxRIGHT | wxTOP, 3); pnl_top->SetSizer(s3); pnl_bottom->SetBackgroundColour(wxColor(45, 45, 45)); this->SetSizerAndFit(s1); } TopPanel::TopPanel(wxWindow* parent, wxSize size) : wxPanel(parent, wxID_ANY, wxDefaultPosition, size) { this->SetSize(500, 30); this->SetId(wxID_ANY); this->SetBackgroundColour(wxColor(45, 45, 45)); } void TopPanel::OnClick(wxCommandEvent &e) { std::cout << e.GetId() << std::endl; std::cout<<"toppanel onclick called"<<std::endl; } //no need for event table entries here
73,092,727
73,097,122
Is there a way to reference/index/pointer an item in a std::stack?
As the title says, using std::stack is there a way to reference any item by reference/index/pointer without popping? If not how could I achieve this? My use case is, I am making a vm for learning and I want to reference the stack items in the std::stack so I can push and access my local stack variables. I originally was going to just make a stack implementation - but I have the stl! I am guessing I may have to roll my own because the items are immutable, and I haven't seen any docs stating it :( My use case (asm ; c++) mov DWORD PTR [rbp-4], 123 ; stack.push(123); mov DWORD PTR [rbp-8], 321 ; stack.push(321); add DWORD PTR [rbp-4], 1 ; stack[?] = stack[?] + 1;
Yes, there is an easy way to access the data through its underlying container. Normally, all this is not necessary because you always can use the underlying container in the first place. But if you want to do that for exceptional purposes, then simply take the address of the top(). This will be the last element in the underlying container. And if you subtract the size() of the stack (corrected by 1), then you have a pointer to the beginning of the underlying container. And then you can use the subscript operator [] as expected. Please see the following example: #include <vector> #include <stack> #include <iostream> #include <algorithm> #include <iterator> using Number = int; using UnderlyingContainer = std::vector<Number>; using Stack = std::stack< Number, UnderlyingContainer>; using StackIterator = Number *const; int main() { // Put the test data onto the stack Stack myStack{ UnderlyingContainer {1,2,3,4,5} }; if (not myStack.empty()) { // Get "iterators" StackIterator end = &myStack.top() + 1; StackIterator begin = end - myStack.size(); Number *const & stk = begin; for (size_t i{}; i < myStack.size(); ++i) stk[i] = stk[i] + 10; for (size_t i{}; i < myStack.size(); ++i) std::cout << stk[i] << '\n'; std::transform(begin, end, begin, [](const Number n) {return n - 10; }); std::copy(begin, end, std::ostream_iterator<Number>(std::cout, "\n")); } } So, it looks like we found what you want to have, but in reality, we simply work on the underlying container. But as said, there are sometimes reasons to do so . . .
73,092,753
73,156,771
Problem building C++ binary using vcpkg and cmake in Github action macos-12
Works fine building on Linux and Windows. But in macos I get: /usr/local/bin/g++-11 -isysroot /Applications/Xcode_13.4.1.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/Calculator_Test.dir/src/speedtest.cpp.o CMakeFiles/Calculator_Test.dir/src/tests.cpp.o -o Calculator_Test ../libCalculator.a ../vcpkg_installed/x64-osx/debug/lib/libCatch2d.a ../vcpkg_installed/x64-osx/debug/lib/manual-link/libCatch2Maind.a ../vcpkg_installed/x64-osx/debug/lib/libCatch2d.a Undefined symbols for architecture x86_64: "__ZN5Catch24translateActiveExceptionB5cxx11Ev", referenced from: __ZN5Catch9Benchmark9Benchmark3runINSt6chrono3_V212steady_clockEEEvv in speedtest.cpp.o "__ZN5Catch9Benchmark6Detail15analyse_samplesEdjN9__gnu_cxx17__normal_iteratorIPdSt6vectorIdSaIdEEEES8_", referenced from: __ZN5Catch9Benchmark6Detail7analyseINSt6chrono8durationIdSt5ratioILl1ELl1000000000EEEEN9__gnu_cxx17__normal_iteratorIPS7_St6vectorIS7_SaIS7_EEEEEENS0_14SampleAnalysisIT_EERKNS_7IConfigENS0_11EnvironmentISG_EET0_SN_ in speedtest.cpp.o Running the following works fine and without error: cmake --preset=${{ matrix.preset }} -B build -DCalculator_Test=1 -DCMAKE_C_COMPILER=gcc-11 -DCMAKE_CXX_COMPILER=g++-11 -DCMAKE_VERBOSE_MAKEFILE=1 "preset" is just setting the CMAKE_TOOLCHAIN_FILE to the one provided by vcpkg and the cmake generator to "Unix Makefiles" From CMakeLists.txt used: set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) ... find_package(Catch2 CONFIG REQUIRED) target_link_libraries(Calculator_Test PRIVATE Calculator Catch2::Catch2 Catch2::Catch2WithMain ) But when compiling is when it fails cmake --build build My question is why does it fail and how to fix it? Is it C++20 that is the problem or is it CMake, vcpkg or something I must do on macos. I'm no macos expert :(
Solved the problem by setting the environmental variables to the correct compiler before setting up vcpkg. In the github actions yml file: - name: Set C++/C compiler on macOs shell: bash run: echo "CC=gcc-11" >> $GITHUB_ENV; echo "CXX=g++-11" >> $GITHUB_ENV; cat "$GITHUB_ENV" if: runner.os == 'macOs' The build step (without specifying the c/c++ compiler): cmake --preset=${{ matrix.preset }} -B build -DCalculator_Test=1 -DCMAKE_VERBOSE_MAKEFILE=1 My assumptions is that the linking of the dependency binaries failed earlier due to being compiled with a different compiler than the application itself.
73,093,306
73,109,037
MariaDB C++ Connector errors when attempting connections from multiple threads
Using the MariaDB C++ Connector on ubuntu 20.04, and gcc compiler. During load test of a webserver application it was discovered that anytime there was more than a single concurrent connection the server would crash. This was narrowed down to the connect member of the mariadb driver. The errors that were being reported were always one of the following two: terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not valid Aborted (core dumped) terminate called after throwing an instance of 'std::invalid_argument' what(): stoi Aborted (core dumped) As it wouldn't be feasible to post the source of the server, I have reproduced a minimal working example that uses only standard library and mariadb/conncpp.hpp: #include <mariadb/conncpp.hpp> #include <iostream> #include <thread> #include <string> sql::Driver* driver = sql::mariadb::get_driver_instance(); sql::SQLString connectionUrl = "jdbc:mariadb://localhost:3306/the_database_name"; sql::Properties properties = {{"user", "the_username"}, {"password", "the_password"}}; int main() { // simulate 2 concurrent connections each making 500 requests std::vector<std::function<void()>> t1cbs; std::vector<std::function<void()>> t2cbs; for(int i = 0; i < 500; i++) // if does not fail for you at 500 up the number until it does { t1cbs.push_back([&]{ std::unique_ptr<sql::Connection> conn(driver->connect(connectionUrl, properties)); std::cout << "t1:" << conn->getHostname().c_str() << std::endl; }); // comment out this block to keep the second thread from executing, and you will see // that no errors occur t2cbs.push_back([&]{ std::unique_ptr<sql::Connection> conn(driver->connect(connectionUrl, properties)); std::cout << "t2:" << conn->getHostname().c_str() << std::endl; }); } std::thread t1([&]{ for(auto& cb : t1cbs) cb(); }); std::thread t2([&]{ for(auto& cb : t2cbs) cb(); }); t1.join(); t2.join(); return 0; } Curious if there's something perhaps I'm not seeing that's going on that someone else might be able to point out? Although after going through the documentation, it seems pretty straight forward...the only thing maybe is that something's going on in the driver->connect that's not thread safe maybe? Not sure...quite confused...any ideas greatly appreciated! EDIT After some more research I discovered the following example where it's mentioned that if you have multiple threads then issues could occur...however still trying to figure out how one might circumvent this.
It is a bug in Connector/C++. To track progress, please check https://jira.mariadb.org/browse/CONCPP-105
73,093,514
73,094,498
Is it possible to create variables based on the amount of arguments in a function?
For example, I have a thread class with a template constructor which can take in an undefined amount of arguments: template<typename _FunctionType, typename ... _ArgType> thread(const _FunctionType* function, _ArgType ... arguments) { _FunctionType Function1; // Creates variable for function _ArgType Argument1; // Creates a variable for each argument given _ArgType Argument2; ... } Is it possible to create a variable for each argument given. If so, how could I do this?
You could write template specialization for functions with 0, 1, 2, 3, 4, 5, ... arguments but that defeats the purpose of having a template. You can't really give each argument a unique name but you can put them into a std::tuple. #include <tuple> template<typename _FunctionType, typename ... _ArgType> void thread(const _FunctionType* function, _ArgType ... arguments) { _FunctionType function_{function}; // Creates variable for function std::tuple<_ArgType...> arguments_{arguments...}; }
73,093,575
73,093,701
Call overloaded, derived function from C++ class on base object does not call the overloaded function
Here is a simplified example (OnlineGDB): #include <iostream> using namespace std; class Base { public: virtual ~Base() {} virtual int test(Base* parent) = 0; }; class Test : public Base { public: ~Test() {} int test(Base* parent) { return 10; } int test(Test* parent) { return 20; } }; int main(int argc, char* argv[]) { Test* test = new Test(); Base* base = test; cout << test->test(test) << endl; // prints 20 cout << base->test(test) << endl; // prints 10 return 0; } I would expect both calls to return 20, because the argument is of type Test, but the second call returns 10. I know I could do dynamic_cast<Test*>(base)->test(test) and it works again, but in reality I have more classes that are derived from Base. Of course I could do sth. like this: auto test1 = dynamic_cast<Test*>(base); if (test1) { test1->test(test); } auto test2 = dynamic_cast<Test2*>(base); if (test2) { test2->test(test); } ... But for any new class derived from Base this would need to be adjusted and there are multiple sections in the code that have to do this. Is there any way, I can keep the base->test(test) or sth. similar to get the "right" value based on the argument type?
When you cast a class, the most specific information is related to the type in the hierarchy you are casting it to. Base vtable doesn't have that overload so there's no way the compiler can know at compile time that another overload exists. If you think about how the dynamic dispatch is implemented it's rather trivial why your code is not working and I don't see how it could. You should provide the exact problem you are trying to solve because there could be a different solution to what you're trying to do, stated as it is it looks like an XY problem.
73,094,049
73,094,124
How to get unique elements from vector using stl?
I have a vector of strings. For now take: std::vector<std::string>{ "one","two","three","two","ten","six","ten"....... } Now I want to filter out only unique strings in the vector, and in the same order as they are. Is there a standard library function for this? EDIT: I need to discard the repeated values.
If you want to remove the duplicate while keeping the order of the elements, you can do it (inplace) in O(n log(n)) like this: std::vector<std::string> v{"one", "two", "three", "two", "ten", "six", "ten"}; // Occurrence count std::map<std::string, int> m; auto it = std::copy_if(v.cbegin(), v.cend(), v.begin(), [&m](std::string const& s) { return !m[s]++; }); // ^ keep s if it's the first time I encounter it v.erase(it, v.end()); Explanation: m keeps track of the number of times each string has already been encountered while scanning through v. The copy_if won't copy a string if it has already been found. If you want to remove all the elements that are duplicated, you can do it (inplace) in O(n log(n)) like this: // Occurrence count std::map<std::string, int> m; // Count occurrences of each string in v std::for_each(v.cbegin(), v.cend(), [&m](std::string const& s) { ++m[s]; } ); // Only keep strings whose occurrence count is 1. auto it = std::copy_if(v.cbegin(), v.cend(), v.begin(), [&m](std::string const& s) { return m[s] == 1; }); v.erase(it, v.end());
73,094,942
73,095,300
assignment of read-only location - Boost Geometry Register Point 2D
I am currently trying to implement a motion-planning algorithm and have been using Boost's RTree to do so. Up until now, the RTree has stored std::pair<boost::geometry::model::point<double, 2, bg::cs::cartesian>, unsigned int> and has worked just fine in answering nearest neighbor queries. Externally, I make use of a custom struct called Node, each of which corresponds to a point in the RTree. I maintain a vector of Nodes so that the ids of the output pairs from the RTree queries can be used as indices to be looked up in the vector. However, I want to eliminate the use of this large vector to see its results on time and space performance of my algorithm. To do this, I want to replace the use of point in the pairs with Nodes, so that the Nodes are directly output in the query results. To do this I have used boost geometry 2d point registering, with the following code: #include <algorithm> #include <iostream> #include <cmath> #include <stdlib.h> #include <stdio.h> #include <string> #include <vector> #include <bits/stdc++.h> #include <boost/geometry.hpp> #include <boost/geometry/geometry.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/geometries/box.hpp> #include <boost/geometry/geometries/register/point.hpp> #include <boost/geometry/index/rtree.hpp> #include <SFML/Graphics.hpp> #include <SFML/Window.hpp> #include <chrono> using namespace std; namespace bg = boost::geometry; namespace bgi = boost::geometry::index; typedef bg::model::point<double, 2, bg::cs::cartesian> point; typedef bg::model::box<point> box; struct Node { Node *parent; point pos; }; typedef pair<Node, unsigned int> ptval; typedef pair<box, unsigned int> boxval; BOOST_GEOMETRY_REGISTER_POINT_2D(Node, double, bg::cs::cartesian, pos.get<0>(), pos.get<1>()); int main() { cout << "hi" << endl; return 0; } However, a strange error results: In file included from rrt.cpp:13: rrt.cpp: In static member function 'static void boost::geometry::traits::access<Node, 0>::set(Node&, const double&)': rrt.cpp:45:1: error: assignment of read-only location 'p.Node::pos.boost::geometry::model::point<double, 2, boost::geometry::cs::cartesian>::get<0>()' BOOST_GEOMETRY_REGISTER_POINT_2D(Node, double, bg::cs::cartesian, pos.get<0>(), pos.get<1>()); This is odd as there are no const declarations anywhere here. I'm guessing it has to do with something inside of the hood of the get<>() functions, but I'm not sure exactly what it is. Any help is appreciated, as I've not found this issue anywhere online.
What version of boost is that? BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET takes 7 parameters, not 5, and it has done so ever since the source file appeared in January 2010, which means Boost 1.47.0. Looking at the docs, it looks like the () are not supposed to be included on the member functions anyways. Finally, you have bg::get<0> in your question code, but since that doesn't even match with the error message you show, I'm assuming that's a simple mistake in the question. Here's a little test program with the fixes I think you wanted: Live On Coliru #include <algorithm> #include <boost/geometry.hpp> #include <boost/geometry/geometries/box.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/geometries/register/point.hpp> #include <boost/geometry/geometry.hpp> #include <boost/geometry/index/rtree.hpp> #include <chrono> #include <iostream> namespace bg = boost::geometry; namespace bgi = boost::geometry::index; typedef bg::model::point<double, 2, bg::cs::cartesian> point; typedef bg::model::box<point> box; struct Node { Node* parent; point pos; }; using ptval = std::pair<Node, unsigned int>; using boxval = std::pair<box, unsigned int>; BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET( // Node, double, bg::cs::cartesian, // pos.get<0>, pos.get<1>, pos.set<0>, pos.set<1>) int main() { { bgi::rtree<ptval, bgi::rstar<16>> index; Node n{nullptr, {}}; bg::assign_values(n.pos, 10.0, 10.0); int idx = 0; index.insert({n, idx++}); for (auto pt : { point{20.0, 10.0}, {20.0, 20.0}, {10.0, 20.0} }) { bg::assign(n.pos, pt); index.insert({n, idx++}); } for (auto& [g, id] : index) { std::cout << id << ": " << bg::wkt(g) << '\n'; } } { bgi::rtree<boxval, bgi::rstar<16>> index; index.insert(boxval{{{1, 2}, {3, 4}}, 12}); for (auto& [g, id] : index) { std::cout << id << ": " << bg::wkt(g) << '\n'; } } } Printing 0: POINT(10 10) 1: POINT(20 10) 2: POINT(20 20) 3: POINT(10 20) 12: POLYGON((1 2,1 4,3 4,3 2,1 2))
73,095,016
73,095,040
list.remove_if() crashing the program
I'm working on a game and I'm trying to add collectables. I'm trying to remove the object from the list after the player has collided with it, but it ends up crashing and says: Unhandled exception thrown: read access violation. __that was 0xDDDDDDE9. It says this on the for loop statement, but I think it has to do with the remove_if() function. Here is my code: for (sf::RectangleShape rect : world1.level1.brainFrag) { collides = milo.sprite.getGlobalBounds().intersects(rect.getGlobalBounds()); if (collides == true) { world1.level1.brainFrag.remove_if([rect](const sf::RectangleShape val) { if (rect.getPosition() == val.getPosition()) { return true; } else { return false ; } }); brainFrag -= 1; collides = false; } } if (brainFrag == 0) { milo.x = oldPos.x; milo.y = oldPos.y; brainFrag = -1; }
I don't understand your approach, you loop the rects, then when you find the one you want to remove, you search for it again through list<T>::remove_if. I think that you forgot about the fact that you can use iterators in addition to a range-based loop: for (auto it = brainFrag.begin(); it != brainFrag.end(); /* do nothing */) { bool collides = ...; if (collides) it = world1.level1.brainFrag.erase(it); else ++it; } This allows you to remove the elements while iterating the collection because erase will take care of returning a valid iterator to the element next to the one you removed. Or even better you could move everything up directly: brainFrag.remove_if([&milo] (const auto& rect) { return milo.sprite.getGlobalBounds().intersects(rect.getGlobalBounds()) } A side note: there's no need to use an if statement to return a boolean condition, so you don't need if (a.getPosition() == b.getPosition() return true; else return false; You can simply return a.getPosition() == b.getPosition();
73,095,031
73,095,047
braced-initialization allows creation of temporary of a *private* struct
I just read the following article from Raymond Chen's excellent 'The Old New Thing': https://devblogs.microsoft.com/oldnewthing/20210719-00/?p=105454 I have a question about this, best described in the following code snippet. Why is the initialization of 'x3' allowed at all? I don't see any semantic difference between the initialization of 'x2' and 'x3' below. #include <memory> class X { struct PrivateTag {}; // default constructor is *NOT* explicit public: X(PrivateTag) {} static auto Create() -> std::unique_ptr<X> { return std::make_unique<X>(PrivateTag{}); } }; int main() { auto x1 = X::Create(); // ok: proper way to create this //auto x2 = X(X::PrivateTag{}); // error: cannot access private struct auto x3 = X({}); // ok: why ?! }
Accessibility restricts only which names may be written out explicitly. It does in no way prevent usage of a type. It is always possible to e.g. use decltype on a function returning the private type and then give it a new name and access it fully through that name or to use template argument deduction to give inaccessible types new aliases through which they can be accessed. The best you can do is to make it hard for a user to accidentally misuse the constructor by employing methods as discussed in the linked blog post, but if a user is determined enough, they can pretty much always obtain a fully accessible alias for PrivateTag and use the constructor anyway. auto x3 = X({}); does not spell out the member classes name, so accessibility of it doesn't matter. auto x2 = X(X::PrivateTag{}); does spell the name of the member class, so accessibility needs to be considered, which makes it ill-formed since PrivateTag is private and inaccessible in the context where it is named. Here is an example of circumventing the private tag trick, no matter whether the adjustment suggested in the blog post is made: struct any_convert { template<typename T> operator T() const { // Here `T` becomes an alias for `PrivateTag` // but is completely accessible. return T{}; } }; //... auto x4 = X(any_convert{});
73,095,189
73,097,589
rust libclang, why am I parsing only c functions from a cpp file?
I am trying to write a rust script that parses a C++ file, finds all extern C declared functions and prints them out. To that effect I have this first attempt: use clang::*; use clap::{Arg, App}; fn main() { let matches = App::new("Shared C++ API parser") .version("0.0.1") .author("Makogan") .about("Parse a cpp file that exposes functions to be loaded at runtime from \ A shared object (.so/.dll).") .arg(Arg::with_name("file") .short('f') .long("file") .takes_value(true) .help("The cpp file that will be parsed") .required(true)) .get_matches(); let cpp_file = matches.value_of("file").unwrap(); println!("The file passed is: {}", cpp_file); let clang = Clang::new().unwrap(); let index = Index::new(&clang, false, false); let tu = index.parser(cpp_file).parse().unwrap(); let funcs = tu.get_entity().get_children().into_iter().filter( |e| { e.get_kind() == EntityKind::FunctionDecl }).collect::<Vec<_>>(); for func_ in funcs { let type_ = func_.get_type().unwrap(); let size = type_.get_sizeof().unwrap(); println!("func: {:?} (size: {} bytes)", func_.get_display_name().unwrap(), size); } } I am giving it a true cpp file with lots of functions, this is one such declared funciton: void DrawOffScreen( void* vk_data_ptr, const NECore::RenderRequest& render_request, const NECore::UniformBufferDataContainer& uniform_container); When I give it a very very simple file I stil don't get an output extern "C" { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wreturn-type-c-linkage" void InitializeRendering(void* window, bool use_vsync) { } } If I comment out the extern C part I do get the correct output. It seems that when the defientiion is inside an extern C block clang thinks the funciton is undeclared: Some(Entity { kind: UnexposedDecl, display_name: None, location: Some(SourceLocation { file: Some(File { path: "/path/dummy.cpp" }), line: 1, column: 8, offset: 7 }) }) What do I do?
UnexposedDecl is actually not the function definition, but the extern 'C' itself. If you print all items recursively, you will see what the tree actually looks like: fn print_rec(entity: Entity, depth: usize) { for _ in 0..depth { print!(" "); } println!("{:?}", entity); for child in entity.get_children() { print_rec(child, depth + 1); } } fn main() { // ... print_rec(tu.get_entity(), 0); } Entity { kind: TranslationUnit, display_name: Some("simple.cpp"), location: None } Entity { kind: UnexposedDecl, display_name: None, location: Some(SourceLocation { file: Some(File { path: "simple.cpp" }), line: 1, column: 8, offset: 7 }) } Entity { kind: FunctionDecl, display_name: Some("InitializeRendering(void *, bool)"), location: Some(SourceLocation { file: Some(File { path: "simple.cpp" }), line: 7, column: 6, offset: 105 }) } Entity { kind: ParmDecl, display_name: Some("window"), location: Some(SourceLocation { file: Some(File { path: "simple.cpp" }), line: 7, column: 32, offset: 131 }) } Entity { kind: ParmDecl, display_name: Some("use_vsync"), location: Some(SourceLocation { file: Some(File { path: "simple.cpp" }), line: 7, column: 45, offset: 144 }) } Entity { kind: CompoundStmt, display_name: None, location: Some(SourceLocation { file: Some(File { path: "simple.cpp" }), line: 8, column: 1, offset: 155 }) } So your actual problem is that you only iterate over the topmost level of the tree, and don't recurse into the segments. To iterate recursively, use visit_children() instead of get_children(): use clang::*; use clap::{App, Arg}; fn main() { let matches = App::new("Shared C++ API parser") .version("0.0.1") .author("Makogan") .about( "Parse a cpp file that exposes functions to be loaded at runtime from \ a shared object (.so/.dll).", ) .arg( Arg::with_name("file") .short('f') .long("file") .takes_value(true) .help("The cpp file that will be parsed") .required(true), ) .get_matches(); let cpp_file = matches.value_of("file").unwrap(); println!("The file passed is: {}", cpp_file); let clang = Clang::new().unwrap(); let index = Index::new(&clang, false, false); let tu = index.parser(cpp_file).parse().unwrap(); let mut funcs = vec![]; tu.get_entity().visit_children(|e, _| { if e.get_kind() == EntityKind::FunctionDecl { funcs.push(e); EntityVisitResult::Continue } else { EntityVisitResult::Recurse } }); for func_ in funcs { let type_ = func_.get_type().unwrap(); let size = type_.get_sizeof().unwrap(); println!( "func: {:?} (size: {} bytes)", func_.get_display_name().unwrap(), size ); } } The file passed is: simple.cpp func: "InitializeRendering(void *, bool)" (size: 1 bytes)
73,095,254
73,095,312
How is vector<vector<int>> "heavier" than vector<pair<int,int>>?
During a recent interview, I suggested using vector<pair<int,int>> over vector<vector<int>> since we only wanted to store two values for every entry in the vector. I said something to the tune of "we should use vector<pair<int,int>> over vector<vector<int>> since the latter is heavier than the former". After the coding session was over, they said it was a good idea to use pair over a vector and asked me to elaborate what I meant by "heavier" earlier. I wasn't able to elaborate, unfortunately. Yes, I know we can enter only two values in a pair but many more in a vector and that vector gets resized automatically when its size==capacity, etc. but how should I have answered their question - why specifically was using vector<pair<int,int>> better than vector<vector<int>>? What extra things are done in the latter case?
Each vector is a single contiguous area of memory, dynamically allocated. Let's say that you have 1000 values you'll be working with. std::vector<std::pair<int, int>> This gets you a single, contiguous block of memory, for 2000 integers. std::vector<std::vector<int>> This gets you a single contiguous block of memory for 1000 vectors. Each one of those 1000 std::vectors gets you another contiguous block of memory for just two integers. So, instead of one single contiguous block of memory, for this data structure, it will consist of 1001 blocks of memory scattered all over. You have no guarantees, whatsoever, that all those blocks of memory will be contiguous, one after another. Each dynamic memory allocation comes at a cost. The cost is fairly small but it adds up very, very quickly. A single penny is easily ignored. A thousand pennies should be enough to get you a cup of coffee at Starbucks. Furthermore, modern CPUs are very, very good at accessing contiguous blocks of memory. Iterating over a single contiguous block of memory to add up two thousand ints will be much, much faster than doing the same over a thousand disjointed sections of memory.
73,095,639
73,095,654
C or C++ : How to keep just "one block in memory" at the time?
In "Introduction to Algorithms" there is the following exercise: Consider implementing a stack in a computer that has a relatively small amount of fast primary memory and a relatively large amount of slower disk storage. The operations PUSH and POP work on single-word values. The stack we wish to support can grow to be much larger than can fit in memory, and thus most of it must be stored on disk. ... ... A simple, but inefficient, stack implementation keeps the entire stack on disk. Because disk operations are relatively expensive, now consider a stack implementation in which we keep one page of the stack in memory. (We also maintain a small amount of memory to keep track of which page is currently in memory.) We can perform a stack operation only if the relevant disk page resides in memory. If necessary, we can write the page currently in memory to the disk and read in the new page from the disk to memory. If the relevant disk page is already in memory, then no disk accesses are required. ... I want to implement this in actual code in C or C++. I know how to use mmap() and I can use memory-mapped disk files for this, but I don't know how to implement "a stack implementation in which we keep one page of the stack in memory". Is there a way to manage memory as C/C++ pointers on a page-by-page basis?
You DON'T. You write the code with the mmapped stack and count the number of times you change page in simulation and let the OS cache as much as it wants. The best way to track page changes is in the push() and pop() functions. Cast the pointer to an integer, use a mask to get rid of the low bits and compare to previous and see if it changed or not. When you reach the end of your simulated run, you output how many times you had to swap pages in RAM. You don't actually force it to disk every time. That's totally unnecessary for the learning environment.
73,095,647
73,095,753
why regular expression match result is empty
this is code #include <iostream> #include <regex> using namespace std; static void search_by_regex(const char *regex_s, const string &s) { // ① regex reg_ex(regex_s); smatch match_result; // ② cout.width(14); // ③ if (regex_search(s, match_result, reg_ex)) { // ④ cout << regex_s << ": \"" << match_result[0] << "\"" << endl; // ⑤ } } int main() { string s("_AaBbCcDdEeFfGg12345!@#$% \t"); // ⑥ search_by_regex("[[:alnum:]]{5}", s); // ⑦ search_by_regex("\\w{5,}", s); // ⑧ search_by_regex(R"(\W{3,5})", s); // ⑨ search_by_regex("[[:digit:]]*", s); // ⑩ search_by_regex(".+", s); // ⑪ search_by_regex("[[:lower:]]?", s); // ⑫ return 0; } this is output: [[:alnum:]]{5}: "AaBbC" \w{5,}: "_AaBbCcDdEeFfGg12345" \W{3,5}: "!@#$%" [[:digit:]]*: "" .+: "_AaBbCcDdEeFfGg12345!@#$% " [[:lower:]]?: "" I think the result is strange. Why the result of a regular expression [[:digit:]]* match is empty? Why the result of a regular expression [[:lower:]]* match is empty?
In short With your current setup, you will return after your first match, as you did not set the global flag (/.../g). Consider the following tokens: ? or *. They will return a null match ("") if nothing matches immediately. Your regex, having such tokens, will return a null match if the first character does not match and the g flag is not set, which is the case. See the demonstration below using your example with interactive links for you to try and experiment. Example using [[:lower:]]?: The regex starts at the beginning of the line, and is looking for something that will match either a lower case, or nothing. The first character ('_') is not a lower case character, therefore it defaults to nothing (?). One of two things may happen next: Without the global flag enabled (/[[:lower:]]?/) the regex returns the match ("") as soon as found. See example on regex101.com or see the little purple-ish line at the start on the following figure: With the global flag enabled (/[[:lower:]]?/g), the regex continues to search for matches until the string runs out, then returns an array of matches. See example on regex101.com or see the multiple purple-ish lines (match end positions), and blue highlights (matches): Hope this helps :)
73,095,700
73,095,855
Segmentation fault on vector class implementation
As for many coding tests STL is not allowed so I am trying to implement vector class. To represent the graph I am using an adjacency list. It's giving me segmentation fault at new_allocation method. Also sometimes I get correct output when I run code but when I debug I get SegFault. Following is my code. #include <iostream> using namespace std; template <typename T> class vector{ T *arr; int s; int c; void new_allocation(){ T *temp = new T[s + 10]; // SEGMENTATION FAULT HERE c = s + 10; for (int i = 0; i < s; i++) temp[i] = arr[i]; arr = temp; delete[] temp; } public: vector() { s = c = 0; } vector(int userVectorSize){ s = c = userVectorSize; arr = new T[userVectorSize]; } void push_back(T data){ if (s == c) new_allocation(); arr[s] = data; s++; } T operator[](int index){ return arr[index]; } int size() { return s; } }; int main(){ int n, m; cin >> n >> m; vector<int> graph[n + 1]; for (int i = 0; i < m; i++){ int v1, v2; cin >> v1 >> v2; graph[v1].push_back(v2); graph[v2].push_back(v1); } for (int i = 1; i <= n; i++){ cout << i << " -> "; for (int k = 0; k < graph[i].size(); k++) cout << graph[i][k] << " "; cout << endl; } }
please initialize the arr in the default ctor: vector() { s = c = 0; arr = nullptr; // (1) } As pm100 mentioned, please pick up the right array to delete[]. void new_allocation() { T *temp = new T[s + 10]; // SEGMENTATION FAULT HERE c = s + 10; for (int i = 0; i < s; i++) temp[i] = arr[i]; // (2) if (arr != nullptr) { delete[] arr; } arr = temp; } The reason is that your arr is pointed to arbitrary memory by default, so it will still report a Segmentation fault when you try to delete[] arr. #include <iostream> using namespace std; template <typename T> class vector { T *arr; int s; int c; void new_allocation() { T *temp = new T[s + 10]; // SEGMENTATION FAULT HERE c = s + 10; for (int i = 0; i < s; i++) temp[i] = arr[i]; if (arr != nullptr) { delete[] arr; } arr = temp; } public: vector() { s = c = 0; arr = nullptr; } vector(int userVectorSize) { s = c = userVectorSize; arr = new T[userVectorSize]; } void push_back(T data) { if (s == c) new_allocation(); arr[s] = data; s++; } T operator[](int index) { return arr[index]; } int size() { return s; } }; int main() { int n, m; cin >> n >> m; vector<int> graph[n + 1]; for (int i = 0; i < m; i++) { int v1, v2; cin >> v1 >> v2; graph[v1].push_back(v2); graph[v2].push_back(v1); } for (int i = 1; i <= n; i++) { cout << i << " -> "; for (int k = 0; k < graph[i].size(); k++) cout << graph[i][k] << " "; cout << endl; } }
73,095,750
73,103,885
Method DrawRectanglePro() not rendering rectangle
I have been trying to test out raylib and I am trying to render rectangles at an angle, but I am unsure as to why they will not render. The method DrawRectangle() does work, despite DrawRectanglePro() not working. #include <iostream> #include "raylib.h" int main() { InitWindow(800, 800, "More Raylib Practice"); SetWindowState(FLAG_VSYNC_HINT); while (!WindowShouldClose()) { BeginDrawing(); ClearBackground(BLACK); DrawRectangle(10, 10, 10, 10, RED); //normal rectangle DOES render Rectangle rec = { 10, 10, 10, 10 }; DrawRectanglePro(rec, { 400, 400 }, (float)45, WHITE); //angled rectangle doesn't? EndDrawing(); } CloseWindow(); return 0; }
It looks like you're misusing the origin parameter, in your case { 400, 400 }. The origin parameter is used to set the origin of the draw point from the referenced rectangle. Your code is saying, on a 10 x 10 square, move right 400, and down 400, then draw that at 10, 10. If you setup a 2d camera you would find your white triangle 400 ish pixels up and to the left, off screen. Most of the time you want to change an origin is to the center of the rectangle or texture. This lets you rotate something on the center as opposed to the top left corner of the texture. In summary, here's the corrected code: #include <iostream> #include "raylib.h" int main() { InitWindow(800, 800, "More Raylib Practice"); SetWindowState(FLAG_VSYNC_HINT); while (!WindowShouldClose()) { BeginDrawing(); ClearBackground(BLACK); DrawRectangle(10, 10, 10, 10, RED); Rectangle rec = { 10, 10, 10, 10 }; DrawRectanglePro(rec, { 0, 0 }, (float)45, WHITE); //Set origin to 0,0 EndDrawing(); } CloseWindow(); return 0; }
73,095,828
73,097,668
Maximal value of the Boost Multiprecision type 'float128' gives me a compilation error with GCC in C++20 mode
This simple code can't be compiled with the -std=c++20 option: #include <limits> #include <boost/multiprecision/float128.hpp> namespace bm = boost::multiprecision; int main() { auto const m = std::numeric_limits<bm::float128>::max(); } The compilation command and its error output: hekto@ubuntu:~$ g++ -std=c++20 test.cpp In file included from test.cpp:2: /usr/include/boost/multiprecision/float128.hpp: In instantiation of ‘static std::numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::number_type std::numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::max() [with boost::multiprecision::expression_template_option ExpressionTemplates = boost::multiprecision::et_off; std::numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, ExpressionTemplates> >::number_type = boost::multiprecision::number<boost::multiprecision::backends::float128_backend, boost::multiprecision::et_off>]’: test.cpp:8:53: required from here /usr/include/boost/multiprecision/float128.hpp:728:55: error: could not convert ‘boost::multiprecision::quad_constants::quad_max’ from ‘const __float128’ to ‘std::numeric_limits<boost::multiprecision::number<boost::multiprecision::backends::float128_backend, boost::multiprecision::et_off> >::number_type’ {aka ‘boost::multiprecision::number<boost::multiprecision::backends::float128_backend, boost::multiprecision::et_off>’} 728 | static number_type (max)() BOOST_NOEXCEPT { return BOOST_MP_QUAD_MAX; } | ^~~~~~~~~~~~~~~~~ | | | const __float128 Why is that? OS: Xubuntu 20.04.4 LTS Compiler: g++ (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0 Boost: 1.71.0
The documentation states: When compiling with gcc, you need to use the flag --std=gnu++11/14/17, as the suffix 'Q' is a GNU extension. Compilation fails with the flag --std=c++11/14/17 unless you also use -fext-numeric-literals. So you need to specify --std=gnu++20 instead of --std=c++20. The boost documentation is not up-to-date. The flag enables various GNU extensions, one of it being __float128. See example on godbolt. The underlying reason for the compiler error is that without the --std=gnu++17 or --std=gnu++20 flag, _GLIBCXX_USE_FLOAT128 is not defined, meaning BOOST_HAS_FLOAT128 is not defined, meaning __float128 is not recognized as number_kind_floating_point (but as number_kind_unknown). This means that boost::multiprecision::number cannot be implicitly constructed from a __float128 because is_restricted_conversion<__float128, boost::multiprecision::float128_backend>::value is true because bm::detail::is_lossy_conversion<__float128, boost::multiprecision::float128_backend>::value is true, because __float128 is number_kind_unknown instead of number_kind_floating_point. I.e. in short, without gnu++20, the boost::multiprecision::float128 type is not supported.
73,096,623
73,097,080
How to hide another class ui using Qt C++?
I've been trying to hide another class ui, but I can't figure it out. As an example I have the MainWindow class and other two classes. This is a scheme of the MainWindow ui: [---------------][---------------] [ Class A ui ][ Class B ui ] [---------------][---------------] The top & bottom lines are just to outline the window. You can imagine it as a rectangle containing two rectangles with the classes ui inside. When I click on a QPushButton in class A I want to hide class B ui. This is a code snippet: ClassA.h #ifndef CLASSA_H #define CLASSA_H #include <QWidget> namespace Ui { class ClassA; } class ClassA : public QWidget { Q_OBJECT public: explicit ClassA(QWidget *parent = nullptr); ~ClassA(); public slots: void on_pushButton_clicked(); private: Ui::ClassA *ui; }; #endif // CLASSA_H ClassA.cpp #include "classa.h" #include "ui_classa.h" ClassA::ClassA(QWidget *parent) : QWidget(parent), ui(new Ui::ClassA) { ui->setupUi(this); } ClassA::~ClassA() { delete ui; } void classA::on_pushButton_clicked() { // code to hide ClassB ui } ClassB & MainWindow are brand new (standard). ClassB ui contains some labels, pushButtons, ... . MainWindow ui contains two QWidgets that are promoted to ClassA ui & ClassB ui. What code should I write in the on_pushButton_clicked() slot? I've made some tries but nothing seems to work. Any help would be much appreciated.
one way is to add a signal in ClassA and emit it when clicking on the considered push button: #ifndef CLASSA_H #define CLASSA_H #include <QWidget> namespace Ui { class ClassA; } class ClassA : public QWidget { Q_OBJECT public: explicit ClassA(QWidget *parent = nullptr); ~ClassA(); public signals: void notifyButtonClicked(); public slots: void on_pushButton_clicked(); private: Ui::ClassA *ui; }; #endif // CLASSA_H and in classA.cpp we have: void classA::on_pushButton_clicked() { emit notifyButtonClicked(); } now you can write this code in mainwindow constructor (assume _A is an object of ClassA): connect(_A, &ClassA::notifyButtonClicked, this, [] { // some code for hiding ClassB }); I haven't tested this, because I dont have Qt on this machine, but that should work, with possible minor modifications. If any errors appear, let me know and I will help. Also, read the signals and slots documentation.
73,097,179
73,097,238
Accessing C++ struct members by indices and undefined behavior
Say, we would like to access members of a C++ structure by indices. It could be conveniently implemented using unions: #include <iostream> struct VehicleState { struct State { double x, y, v, yaw; }; union { State st; double arr[4]; }; }; int main() { VehicleState state; state.st.x = 1; state.st.y = 2; state.st.v = 3; state.st.yaw = 4; for (auto value : state.arr) std::cout << value << std::endl; } Unfortunately, it is undefined behavior to read from the member of the union that wasn't most recently written. That said, I haven't found any compiler or a platform where it would not work as expected. Could you tell me what was the rationale for calling it undefined behavior rather than standardizing it?
Actually it's perfectly fine to read from a union member other than the one you have written too as long as you only access a common prefix. So union { State st; struct { double x; }; } state; state.st.x = 1; if (state.x == 1) // perfectly fine. The problem is that the rules for the layout of structs is complicated and a lot is implementation defined. The struct with 4 doubles could have padding between doubles for some reason and then your array of doubles wouldn't access the same bytes. Unless the standard starts mandating the padding or describes when padding must be equal for unions to work like you ask this can't be allowed. I recommend watching named tupples
73,097,219
73,097,850
finding max catches if you can move at a certain speed while objects appear at particular timestamps?
I faced this problem in an interview, I couldn't solve it in interview. I recall a similair problem that i solved during IOI though cannot recall it. Given N houses in a line. each of M pokemon makes an appearance at a house exactly once. ex - a pokemon appears for an instant at 5th house at time = 6. another pokemon appears for an instant at 7th house at time = 1. and so on. we start at house P, we can move at speed of X house/sec. find max number of pokemon you can catch? All i can think of is greedy or bruteforce but bruteforce is exponential and greedy is incorrect.
Observation: Each Pokemon disappears right after they appear, so we need to be at a house at time=x to catch the Pokemon. If we can not make it in time, we never stop there. Solution: create a new directed graph G=(V,A) where each v_i in V represents a house h_i = house(v_i) where a Pokemon appears at time t(v_i). Create A containing arc u->v, for each such pair if t(u)+distance(house(u),house(v)) =< t(v). In other words: if it is possible to catch Pokemon at at house(v) after Pokemon at house(u), given the time constraints. Create a root s of the DAG and create an arc s->u for u in V if distance(P, house(u)) <= t(u). Now, for example, with a depth-first search, you can find the longest path and reconstruct the route you take in the original instance.
73,097,221
73,097,679
How can I simplify the function with two loops, or is it better to leave it as it is?
I have two almost identical functions where two loops are the same, but the code inside is different, how can I do it more correctly Leave it as it is or change both functions to one or how you do when faced with such code, just wondering which method do you think is correct . template <class T1> void function_A(T1 & array_test) { for (int h = 0; h < 3; ++h) { for (int i = 0; i < 7; ++i) { // CODE 1 } } } template <class T1> void function_B(T1 & array_test) { for (int h = 0; h < 3; ++h) { for (int i = 0; i < 7; ++i) { // CODE 2 } } } if (functiontest == 0) { function_A(array_test); } if (functiontest == 1) { function_B(array_test); } I'm thinking of doing this, but I'm not sure if it's better than the top option, but inside the function there will be only code without loops, but you will also need to pass three arguments and not one for (int h = 0; h < 3; ++h) { for (int i = 0; i < 7; ++i) { if (functiontest == 0) { function_A(h, i, array_test); } if (functiontest == 1) { function_B(h, i, array_test); } } }
Example (without template, to better show the underlying principle). You can pass the code to test as a std::function. #include <functional> #include <vector> void Test(std::function<void(int,int, std::vector<int>&)> fn, std::vector<int>& array_test) { for (int h = 0; h < 3; ++h) { for (int i = 0; i < 7; ++i) { fn(h, i,array_test); } } } void code_1(int h, int i, std::vector<int>& array_test) { } void code_2(int h, int i, std::vector<int>& array_test) { } int main() { std::vector<int> values{ 1,2,3 }; Test(code_1, values); Test(code_2, values); return 0; }
73,097,240
73,097,335
Problems with cin and reading input
I am new to C++ and I have a problem with cin in my code. When I run this code, after I enter some words, it just skips and ignores the second cin in the code and I don't understand why. I read that it happens because of Enter and Space in the new line, and I should use cin.ignore(), but it still does not work. For the first loop, I use Ctrl+Z and loop ends my problem after that. int main() { vector<string> words; cout << "Enter your words" << endl; for (string input; cin >> input;) { words.push_back(input); cin.ignore(); } cout << "You entered these words:" << endl; for (string a: words) { cout << a << endl; } cin.ignore(); string disliked; cout << "If you have any disliked word please type it " << endl; cin >> disliked; for (int i = 0; i < words.size(); i++) { if (words[i] == disliked) { words[i] = "Bleep"; } } }
for (string input; cin >> input;) { words.push_back(input); cin.ignore(); } So, as you say in a comment, the user ends this loop by entering end of file (ctrl-Z on Windows console). After that, the file is at end. You can not continue reading from it, it is closed. You have to figure out some other way to end this first loop. Suggestions: Instead of reading words, read lines usint std::getline, and if user enters empty line, then end this loop. You then have to split the line into words as a separate step, of course. Add some specific non-letter "word" to mark the end of this loop, such as a lone ".". Also, as long as you are reading words with std::cin >> word, you don't need std::ignore() for anything. Reading into an std::string will skip any leading whitespace automatically.
73,097,267
73,180,619
how to use mold linker with bazel and gcc10?
mold is the latest modern linker with high speed, I want to use it to replace default ld linker when compiling our heavy c++ repository. I use Bazel + GCC 10.2 to compile, and mold docs provide a gcc -B/mold/path solution. However I don't find a way to pass this CLI option to bazel. I tried bazel build --linkopt=-B/usr/local/libexec/mold //src:XXX or --copt=-B/usr/local/libexec/mold, but both don't work, bazel still use old linker. I can ensure mold has been installed on my system, because I can compile c++ helloworld program link by mold directly run g++ -B/usr/local/libexec/mold.
Peterson's answer can work in most cases, but if you are using an outdated Bazel version such as 0.2x like me, there is a bug for Bazel link stage. The bug leads to user link flags always be overwrite by Bazel default link flags. To verify the bug, run bazel build --subcommands --linkopt=-B/any_path <your-target>, and you will see details about link stage flags. In my case, Bazel default flag -fuse-ld=gold and -B/usr/bin always occurs after user flags, so I have to create a soft link /usr/bin/ld.gold -> /usr/local/bin/mold. This workaround works for me. So try: mv /usr/bin/ld.gold /usr/bin/ld.glod.backup ln -s /usr/local/bin/mold /usr/bin/ld.gold
73,097,441
73,097,576
Concept constrained member function having dependent argument types
I was doing some experiments with concepts, and I was trying to have constrained member functions that must be instantiated only if a concept is satisfied: template <typename T> concept Fooable = requires(T o) { o.foo(uint()); }; template <typename T> concept Barable = requires(T o) { o.bar(uint()); }; class Foo { public: using FooType = int; void foo(uint) {} }; class Bar { public: using BarType = double; void bar(uint) {} }; template <typename T> class C { public: void fun(typename T::FooType t) requires Fooable<T> {} void fun(typename T::BarType t) requires Barable<T> {} }; int main() { C<Foo> f; } This piece of code does not compile both on GCC 11.2 and Clang 14, saying: main.cpp: error: no type named 'BarType' in 'Foo' main.cpp: error: no type named 'BarType' in 'Foo' void fun(typename T::BarType t) requires Barable<T> {} ~~~~~~~~~~~~^~~~~~~ main.cpp: note: in instantiation of template class 'C<Foo>' requested here C<Foo> f; ^ However, since I am declaring a C object with Foo type, I expect that the member function fun with BarType would not be instantiated. Could this be both a GCC and Clang bug? Or am I doing something wrong? Is there any way to implement this using concepts?
Since fun is not a template function, typename T::BarType is always instantiated and produces a hard error if T does not have a type alias named BarType. You might want to do template <typename T> class C { public: template<Fooable U = T> requires requires { typename U::FooType; } void fun(typename U::FooType t); template<Barable U = T> requires requires { typename U::BarType; } void fun(typename U::BarType t); }; Given that BarType is associated with the concept Barable, a more appropriate approach would be to redefine your concepts as (I replaced uint() with 0U because there is no so-called uint type in the standard) template<typename T> concept Fooable = requires(T o) { o.foo(0U); typename T::FooType; }; template<typename T> concept Barable = requires(T o) { o.bar(0U); typename T::BarType; }; template <typename T> class C { public: template<Fooable F = T> void fun(typename F::FooType t); template<Barable B = T> void fun(typename B::BarType t); }; which requires that types satisfying Barable must have a type alias named BarType.
73,097,919
73,098,000
how to check a point if it lies inside a rectangle
I have a rectangle Rect (x,y,w,h) and a point P (px, py). x and y are the top left coordinate of the rectangle. w is it's width. h is it's height. px and py are the coordinate of the point P. Does anyone knows the algorithm to check if P lies inside Rect. Surprisingly, I couldn't find any correct answer for my question on the internet. Much appreciate!
The point P(px, py) lies inside the Rectangle with top left pt. coordinates (x,y) and width and height w&h respectively if both the conditions satisfy: x < px < (x+w) y > py > (y-h) Hope this helps :)
73,098,028
73,098,145
Why is the size of the union greater than expected?
#include <iostream> typedef union dbits { double d; struct { unsigned int M1: 20; unsigned int M2: 20; unsigned int M3: 12; unsigned int E: 11; unsigned int s: 1; }; }; int main(){ std::cout << "sizeof(dbits) = " << sizeof(dbits) << '\n'; } output: sizeof(dbits) = 16, but if typedef union dbits { double d; struct { unsigned int M1: 12; unsigned int M2: 20; unsigned int M3: 20; unsigned int E: 11; unsigned int s: 1; }; }; Output: sizeof(dbits) = 8 Why does the size of the union increase? In the first and second union, the same number of bits in the bit fields in the structure, why the different size? I would like to write like this: typedef union dbits { double d; struct { unsigned long long M: 52; unsigned int E: 11; unsigned int s: 1; }; }; But, sizeof(dbits) = 16, but not 8, Why? And how convenient it is to use bit fields in structures to parse bit in double?
members of a bit field will not cross boundaries of the specified storage type. So unsigned int M1: 20; unsigned int M2: 20; will be 2 unsigned int using 20 out of 32 bit each. In your second case 12 + 20 == 32 fits in a single unsigned int. As for your last case members with different storage type can never share. So you get one unsigned long long and one unsigned int instead of a single unsigned long long as you desired. You should use uint64_t so you get exact bit counts. unsigned int could e anything from 16 to 128 (or more) bit. Note: bitfields are highly implementation defined, this is just the common way it usually works.
73,098,525
73,098,570
std::sort not sorting vector properly
I want to sort my vector of pairs by the ratio of the first to the second value of the pair. I am using C++ STL sort function but, I don't know, It is not sorting the vector properly here is my code: comparator bool comparator(const std::pair<int, int> &item1, const std::pair<int, int> &item2) { return (item1.first / item1.second) < (item2.first / item2.second); } sort function call int main() { std::vector<std::pair<int, int>> items = {{4, 5}, {1, 4}, {3, 5}, {6, 7}, {8, 8}}; std::sort(items.begin(), items.end(), comparator); for (auto item : items) std::cout << item.first << ", " << item.second << "\n"; return 0; } my output 8, 8 4, 5 1, 4 3, 5 6, 7 expected output 8, 8 6, 7 4, 5 3, 5 1, 4 I also tried return (double)(item1.first / item1.second) > (double)(item2.first / item2.second); but it is also giving me another output 4, 5 1, 4 3, 5 6, 7 8, 8
It seems you want to compare float results like return (static_cast<double>( item1.first ) / item1.second) < (static_cast<double>( item2.first ) / item2.second); In this case the vector will be sorted in the ascending order and the result will be 1, 4 3, 5 4, 5 6, 7 8, 8 If you want to sort the vector in the descending order then use this return statement return (static_cast<double>( item2.first ) / item2.second) < (static_cast<double>( item1.first ) / item1.second); In this case the output will be 8, 8 6, 7 4, 5 3, 5 1, 4 As for this return statement return (double)(item1.first / item1.second) > (double)(item2.first / item2.second); then in parentheses there is used the integer arithmetic (item1.first / item1.second) So casting to double has no effect for the comparison.
73,098,660
73,103,902
"Merge" two signatures of operator () overload into one in a template class, how?
Let's suppose I have the following class in an header file header.h: #pargma once #include <type_traits> #include <iostream> #include <sstream> struct foo { // Utils struct template <class T, class... Ts> struct is_any: std::disjunction <std::is_same <T, Ts>... >{}; // Standard case template <class T_os, class T, class... Args, typename = std::enable_if_t<is_any <T_os, std::ostream, std::ostringstream>::value>> const foo& operator () ( T_os& os, const T& first, const Args&... args ) const { os << "hello"; return *this; } // Default std::ostream = std::cout case template <class T, class... Args> const foo& operator () ( const T& first, const Args&... args ) const { std::cout << "hello"; return *this; } }; I defined a struct in which I overloaded the () operator two times: in the "standard case" the template is enabled if the T_os type is one of this list (std::ostream, std::ostringstream) and a message is sent to output using the T_os os object. In the "Default std::ostream = std::cout case" the template is called if T_os is not explicitly present and a message is sent to output using the std::ostream std::cout object. A simple usage in main is: #include "header.h" int main() { foo foo_obj; // Standard case foo_obj ( std::cout, "first", "second" ); // Default std::ostream = std::cout case foo_obj ( "first", "second" ); } I want to know if it would be possible to merge the "standard case" operator () overload within the "Default std::ostream = std::cout case" operator () overload, in order to be able to perform the two operations shown in main using only an operator () overload instead of two. Thanks.
You could make operator() a front-end for the real implementation. You can then make it forward the arguments to the real implementation and add std::cout if needed. Example: struct foo { template <class T, class... Args> const foo& operator()(T&& first, Args&&... args) const { if constexpr (std::is_base_of_v<std::ostream, std::remove_reference_t<T>>) { // or std::is_convertible_v<std::remove_reference_t<T>*, std::ostream*> // first argument is an `ostream`, just forward everything as-is: op_impl(std::forward<T>(first), std::forward<Args>(args)...); } else { // add `std::cout` first here: op_impl(std::cout, std::forward<T>(first), std::forward<Args>(args)...); } return *this; } private: // implement the full operator function here. `os` is an `ostream` of some sort: template <class S, class... Args> void op_impl(S&& os, Args&&... args) const { (..., (os << args << ' ')); os << '\n'; } }; Demo I used is_base_of_v<std::ostream, ...> instead of is_same to make it use any ostream (like an ostringstream or ofstream) if supplied as the first argument.
73,098,915
73,098,965
How to convert a string to array of strings made of characters in c++?
How to split a string into an array of strings for every character? Example: INPUT: string text = "String."; OUTPUT: ["S" , "t" , "r" , "i" , "n" , "g" , "."] I know that char variables exist, but in this case, I really need an array of strings because of the type of software I'm working on. When I try to do this, the compiler returns the following error: Severity Code Description Project File Line Suppression State Error (active) E0413 no suitable conversion function from "std::string" to "char" exists This is because C++ treats stringName[index] as a char, and since the array is a string array, the two are incopatible. Here's my code: string text = "Sample text"; string process[10000000]; for (int i = 0; i < sizeof(text); i++) { text[i] = process[i]; } Is there any way to do this properly?
If you are going to make string, you should look at the string constructors. There's one that is suitable for you (#2 in the list I linked to) for (int i = 0; i < text.size(); i++) { process[i] = string(1, text[i]); // create a string with 1 copy of text[i] } You should also realise that sizeof does not get you the size of a string! Use the size() or length() method for that. You also need to get text and process the right way around, but I guess that was just a typo.
73,099,107
73,099,138
How to sort std::multimap entries based on keys and values via custom Compare predicate?
I'm looking for a way to sort std::multimap's entries in ascending order by keys, but if the keys match, in descending order by values. Is it possible to implement with a custom Compare predicate?
Map's Compare predicate only takes keys as arguments. Unfortunately you cannot use values to sort the entries within the same bucket with use of the predicate only. Important - it's still possible to implement such scenario it with other means. Here is the answer how to do it if you are ok to use emplace_hint. The keys are sorted in ascending order by default with use of std::less. In order to implement a custom predicate, you can use a lambda (or any other form of the binary predicate): const auto lessPredicate = [](const MyClass& lhs, const MyClass& rhs) { return lhs.value < rhs.value; }; std::multimap<MyClass, std::string, decltype(lessPredicate)> my_map { lessPredicate };
73,099,409
73,099,555
Making base class protected constructor public in derived class
Can someone please explain why the marked line does not compile? It seems to me that if B2 and D compile, B1 should too. class A1 { protected: A1(int){} }; class B1 : private A1 { public: using A1::A1; }; class A2 { protected: A2(int){} }; class B2 : private A2 { public: B2(int i) : A2(i) {} }; class C { protected: void f(int) {} }; class D : private C { public: using C::f; }; int main() { // B1 b1(1); // error: calling a protected constructor of class 'A1' B2 b2(1); D d; d.f(1); }
using-declaration behaves differently when designating constructors vs other members. For constructors, the visibility of the using-declaration is ignored; if selected by overload resolution, the constructor can be used if it's visible in the base class. For all other members, using-declaration introduces a synonym into the derived class' scope, and that synonym has the visibility of the using-declaration. [namespace.udecl]/19 A synonym created by a using-declaration has the usual accessibility for a member-declaration. A using-declarator that names a constructor does not create a synonym; instead, the additional constructors are accessible if they would be accessible when used to construct an object of the corresponding base class, and the accessibility of the using-declaration is ignored.
73,099,579
73,099,598
cout a string from class outputs a "nan"
I created a class that holds the information about a character in a game. I also created a constructor for it. But when I cout a string or a float from the class, it outputs a "nan" or a weird and long number or just nothing. look at the code:- #include <iostream> #include <conio.h> #include <string> #include <windows.h> using namespace std; class Character { public: string type; string name; float HP; float MP; float str; float def; float agility; int LVL; Character(string atype, string aname, float aHP, float aMP, float astr, float adef, float aagility, int aLVL){ string type = atype; string name = aname; float HP = aHP; float MP = aMP; float str = astr; float def = adef; float agility = aagility; int LVL = aLVL; } }; int main() { Character war("Warrior", "Achilles", 100, 30, 50, 35, 30, 1); cout << war.type << endl; cout << war.name << endl; cout << war.HP << endl; cout << war.MP << endl; cout << war.str << endl; cout << war.def << endl; cout << war.agility << endl; cout << war.LVL << endl; cout << "Test String" << endl; return 0; } and the output is:- //nothing //nothing again 1.08418e-038 1.08418e-038 4.15749e+033 4.19234e-033 nan 36 Test String Please help!
Character(string atype, string aname, float aHP, float aMP, float astr, float adef, float aagility, int aLVL){ string type = atype; string name = aname; float HP = aHP; float MP = aMP; float str = astr; float def = adef; float agility = aagility; int LVL = aLVL; } should be Character(string atype, string aname, float aHP, float aMP, float astr, float adef, float aagility, int aLVL){ type = atype; name = aname; HP = aHP; MP = aMP; str = astr; def = adef; agility = aagility; LVL = aLVL; } Your version creates new variables which hide the class members you are trying to assign to! That's why they have garbage values. The preferred way to do this however is to use an initialiser list Character(string atype, string aname, float aHP, float aMP, float astr, float adef, float aagility, int aLVL) : type(atype) , name(aname) , HP(aHP) , MP(aMP) , str(astr) , def(adef) , agility(aagility) , LVL(aLVL) { }
73,099,621
73,099,653
C++ string and char* difference in example
This is from hackerrank "Inherited Code" example, While this works and what() returns n, if I comment the return in what and uncomment the currently commented part what() returns junk. They look the same to me, what is the difference? /* Define the exception here */ struct BadLengthException : public exception { public: int num; string stra; BadLengthException(int n){ this->num = n; this->stra = to_string(this->num); }; const char * what () const throw () { return this->stra.c_str(); //string a = to_string(this->num); //return a.c_str(); } };
string a is a local (ASDV) in what(). It goes out of scope when you return. a.c_str() is simply a pointer, it's non-owning and thus doesn't extend the lifetime of the char buffer, therefore it's UB. In case of UB, anything can happen, including returning junk.
73,099,837
73,099,911
Why is `std::string_view` not implemented differently?
Given the following code we can see that std::string_view is invalidated when string grows beyond capacity (here SSO is in effect initially then contents are put on the heap) #include <iostream> #include <cassert> #include <string> using std::cout; using std::endl; int main() { std::string s = "hi"; std::string_view v = s; cout << v << endl; s = "this is a long long long string now"; cout << v << endl; } output: hi # so if I store a string_view to a string then change the contents of the string I can be in big trouble. Would it be possible, given the existing std::string implementations to make a smarter string_view? which would not face such a drawback? We could store a pointer to the string object itself and then determine if the string is in SSO more or not and work accordingly.(Not sure how this would work with literal strings though, so maybe that is why it was not done this way?) I am aware that string_view is akin to storing the return value of string::c_str() but given we have this wrapper around std::string I do not think this gotcha would occur to a lot of people using this feature. Most disclaimers are to make sure the pointed to std::string is within scope but this is a different issue altogether.
string_view knows nothing about string. It is not a "wrapper" around a string. It has no idea that std::string even exists as a type; the conversion from string to string_view happens within std::string. string_view has no association with or reliance on std::string. In fact, that is the entire purpose of string_view: to be able to have a non-modifiable sized string without knowing how it is allocated or managed. That it can reference any string type that stores its characters contiguously is the point of the thing. It allows you to create an interface that takes a string_view without knowing or caring whether the caller is using std::string, CString, or any other string type. Since the owning string's behavior is not string_view's business, there is no possible mechanism for string_view to be told when the string it references is no longer valid. We could store a pointer to the string object itself and then determine if the string is in SSO more or not and work accordingly. For the sake of argument, let us ignore that string_view is not supposed to know or care whether its characters come from std::string. Let's assume that string_view only works with std::string (even though that makes the type completely worthless). Even then, this would not work. Or rather, it would only work if the type was functionally no different from a std::string const&. If string_view stores a pointer to the first character and a size, then any modification to the std::string might change this. It could change the size even without breaking small-string optimization. It could change the size without causing reallocation. The only way to correct this is to have the string_view always ask the std::string it references what its character data and size are. And that's no different from just using a std::string const& directly.
73,100,077
73,100,223
why assert(str!=NULL) does not return an error?
Why did this not print an assert error? This is my code: #include<assert.h> #include<stdio.h> int main(){ int n =12; char str[50] = ""; assert(n>=10); printf("output :%d\n",n); assert(str!=NULL); printf("output :%s\n",str); }
char str[50] = ""; This makes str into an array of 50 chars, and initialises the memory to all zeroes (first byte explicitly from "" and rest implicitly, because C does not support partial initialisation of arrays or structs). assert(str!=NULL); When used in an expression, array is treated as pointer to its first element. The first element of the array very much has an address, so it is not NULL. If you want to test if the first element of the array is 0, meaning empty string you need assert(str[0] != '\0'); You could compare to 0, or just say assert(*str);, but comparing to character literal '\0' makes it explicit to the reader of the code, that you are probably testing for string-terminating zero byte, not some other kind of zero, even if for the C compiler they're all the same.
73,100,129
73,100,492
What is a static member function? Can we use a static function to initialize a parent functor?
I ran into a situation where I have two classes, class A is a templated class with a template function F, and B is A's child, which instantiate F. Can I just use a static function to do that? template<typename F> class A{ public: class A(const F& f):_f{f}{} F _f; }; class B: public A<std::function<double(const double&)>>{ public: B():A<std::function<double(const double&)>{fb}{}; static double fb(const double& x){return x;} }; Can I do this? What is the difference between this way, and the way where I initiate the B function using some function defined outside the class? Thanks!
What is a static member function? A function inside a class not bound to class instance. Can we use a static function to initialize a parent functor? Yes. Can I just use a static function to do that? Yes. Can I do this? No, your code has syntax errors. There should be no class before A constructor, and B():A<..... line is missing a >. After fixing errors, you can compile the code. What is the difference between this way, and the way where I initiate the B function using some function defined outside the class? The difference is exactly in that - one is initialized with a function defined outside the class, the other with a function defined inside the class.
73,100,233
73,100,303
how to overload function with different class object c++
You can see in main Func im passing different objects at function, which is overloaded and have different kind of objects, but when i run same account transfer function only run, anyone can guide what im doing wrong, whats need to be done. Easy words there are 3 functions made in class ACI Transfer(double balance, class object) im trying to run all these 3 functions by passing their respected object #include<iostream> using namespace std; class Account { private: double balance; public: Account(){} Account(double balance){ this->balance=balance; } void Deposit(double balance){ cout<<endl<<"Account()"<<endl; this->balance=balance; } void WithDraw(double balance) { cout<<endl<<"Account()"<<endl; if(this->balance>balance){ this->balance=this->balance-balance; } else cout<<endl<<"Error"<<endl; } void CheckBalance(void) { cout<<"Balance: "<<balance; } void setBalance(double balance) { this->balance=balance; } double getBalance(){ return balance; } }; class InterestAccount : public Account { private: double Interest; public: InterestAccount(double Interest,double balance) : Account(balance){ this->Interest=Interest; } InterestAccount(){ Interest=0.30; } void Deposit(double balance) { cout<<endl<<"InterestAcc()"<<endl; balance=balance*Interest; setBalance(balance); } }; class ChargingAccount : public Account{ private: double fee; public: ChargingAccount(){} ChargingAccount(double fee,double balance) : Account(balance) { this->fee=fee; } void WithDraw(double balance){ cout<<endl<<"ChargingAcc()"<<endl; if(getBalance()+3>balance){ balance=getBalance()-balance; setBalance(balance); } else cout<<endl<<" ERROR "<<endl; } }; class ACI : public InterestAccount, public ChargingAccount { public: ACI(){ } ACI(double fee,double balance,double Interest) : InterestAccount(Interest,balance), ChargingAccount(fee,balance) { } void transfer(double balance,Account ACC){ cout<<"Account"; ACC.setBalance(balance); } void transfer(double balance,double fee,InterestAccount IG){ cout<<"InterestAcc"; IG.setBalance(balance); } void transfer(double balance,double fee,ChargingAccount CG){ cout<<"ChargingACC OBJ"; CG.setBalance(balance); } }; int main() { double balance=10000; // cout<<"Enter Balance to transfer: "; // cin>>balance; ChargingAccount CG; InterestAccount IR; ACI obj; obj.transfer(balance,CG); obj.transfer(balance,IR); }
trying to run all these 3 functions by passing their respected object The other two overloaded functions have 3 parameters but you're passing only two arguments when calling the function transfer. Thus, the one ACI::transfer(double ,Account) with 2 parameters is the only viable candidate and will be called both times. To solve this you've to pass exactly 3 arguments so that the respective functions can be called as shown below: int main() { double balance=10000; // cout<<"Enter Balance to transfer: "; // cin>>balance; ChargingAccount CG; InterestAccount IR; ACI obj; //------------------------v----->pass some number here, this calls ACI::transfer(double, double, ChargingAccount) obj.transfer(balance, 5, CG); //------------------------v----->pass some number here, this calls ACI::transfer(double, double, InterestAccount) obj.transfer(balance, 6, IR); } Demo Now the output will be: ChargingACC OBJInterestAcc Method 2 You can also solve this by removing the second parameter from the 2nd and 3rd overload as shown below: class ACI : public InterestAccount, public ChargingAccount { public: ACI(){ } ACI(double fee,double balance,double Interest) : InterestAccount(Interest,balance), ChargingAccount(fee,balance) { } void transfer(double balance,Account ACC){ cout<<"Account"; ACC.setBalance(balance); } //-----------------------------------v----------------------->removed 2nd parameter from here void transfer(double balance,InterestAccount IG){ cout<<"InterestAcc"; IG.setBalance(balance); } //-----------------------------------v----------------------->removed 2nd parameter from here void transfer(double balance,ChargingAccount CG){ cout<<"ChargingACC OBJ"; CG.setBalance(balance); } }; Demo
73,100,757
73,101,339
How would I make sure that the needed headers required in my C++ program are installed on the user's machine?
I have a C++ project that uses the popular Boost library. The problem is, if someone downloads my code off say, Github and tries to build it, it won't work unless they have Boost installed, which could be an inconvenience. I'm just wondering how I would go about making sure these headers are accessible for the user so they can build the app themselves. Would I have to copy them into a separate folder in the directory? Are there better solutions? Thanks!
There are quite a lot of options on how to manage dependencies. In my experience many platforms define it's own conventional way of doing so. E.g. in iOS development people either use CocoaPods or SwiftPackages (and sometimes Carthage). For Android applications, developers usually define dependencies in dependencies block of their Gradle-build script (which essentially takes them from remote repos). There isn't necessary an industry standard, but there is something other developer usually find consistent. As far as I'm concerned, in C++ world the dependencies are expected to be managed via CMake. I wouldn't say that CMake itself defines conventional way of managing dependencies (there is far more than one approach of doing so), but the part which everyone expects is that when your CMake script finishes successfully, it has all dependencies set up. Here are a few options you have when managing dependencies via CMake: find_package - the most widespread way. As a result, this command should end up with include dirs and a library target configured in your cmake script (against which you link your own project). I'm not a big fan of this command to be honest, because it really depends on how the host machine is configured, and you are supposed to write additional Find<Library_name>.cmake files where you give instructions for CMake how to find the given library. Add your dependencies as git submodules in subdirectories of your project and use add_subdirectory on those dependencies in you CMakeLists.txt - my preferable way. First, I like it because it's highly portable, you don't expect the host machine to be configured in any specific way, second, it doesn't spread dependencies beyond the project directory. Last, but not least, the submodules keep state of the repository used, so everyone who clone your code will get exactly the same version of the dependency you use and at the same time they have a possibility to update it (pull more recent version as needed). Package managers (e.g. Conan) - you have already guessed, I think, that dependency management in C++ is not very novice-friendly and there are still some new options being developed to address this issue. Conan is one of such options, and it's compatible with CMake (but it's not very widespread yet). Thanks to flexibility of CMake, you also can add any intermediate steps to ease the installation of dependencies, including, but not limited to automatic git submodules pull and update, or installing some missing tools.
73,100,964
73,101,016
Are there any advantages to pure virtual members (except the human error that they might prevent)?
I have a stack of classes with pure virtual members, it'll be populated by derived non-abstract classes. I'm getting the error: Error C2259 'ABC': cannot instantiate abstract class TEMP c:\program files (x86)\microsoft visual studio\2017\enterprise\vc\tools\msvc\14.16.27023\include\xmemory0 879 This error can be solved by using stack<ABC*>, however heap memory access is slower than stack memory, so I'm thinking about rewriting the base class ABC with no pure virtual members at all. Would there be any drawbacks from this (except the possible human error of whoever might use this code)? Is there a way I can create a stack of classes with pure virtual members on the stack? Or, maybe, am I too paranoid about using the heap? The class (in the original code) would be accessed very frequently. Simplified version of the code below: #include <iostream> #include <stack> class ABC { public: ABC(int& a) : m_a(a) {} ~ABC() {} virtual void do_something() = 0; int m_a; }; class DEF : public ABC { public: DEF(int& a) : ABC(a) {} void do_something() override; ~DEF() {} }; void DEF::do_something() { std::cout << "Hi!\n"; } int main(int argc, char* argv[]) { int x = 123; std::stack<ABC> s; s.push(DEF(x)); }
In this call s.push(DEF(x)); the temporary object of the type DEF is implicitly converted to an object of the type ABC. So if to call the virtual function then the virtual function of the class ABC will be called. You can use the polymorphism when you use pointers or references. Here is your updated program. #include <iostream> #include <stack> class ABC { public: ABC(int& a) : m_a(a) {} ~ABC() {} virtual void do_something() { std::cout << "Bye!\n"; }; int m_a; }; class DEF : public ABC { public: DEF(int& a) : ABC(a) {} void do_something() override; ~DEF() {} }; void DEF::do_something() { std::cout << "Hi!\n"; } int main() { int x = 123; std::stack<ABC> s; s.push(DEF(x)); s.top().do_something(); } The program output is Bye! As you can see there is object slicing. Pay attention to that you need to make the destructor virtual. You could just write in the base class virtual ~ABC() = default;
73,101,505
73,101,604
how to add lambda function or perform custom operation in STL set in c++
I need a set arranges the value in such a way that if the int values are different i need the lexographically greater string to come front else i want the smaller integer to come front set<pair<int,string>,[&](auto &a,auto &b){ if(a.first==b.first)return a.second>b.second; return a.first<b.first; }>;
It seems you mean the following #include <iostream> #include <string> #include <utility> #include <set> #include <tuple> int main() { auto less = []( const auto &p1, const auto &p2 ) { return std::tie( p1.first, p2.second ) < std::tie( p2.first, p1.second ); }; std::set<std::pair<int, std::string>, decltype( less )> s( { { 1, "A" }, { 1, "B" }, { 2, "A" } }, less ); for ( const auto &p : s ) { std::cout << p.first << ' ' << p.second << '\n'; } } The program output is 1 B 1 A 2 A You could use also the constructor without the initializer list std::set<std::pair<int, std::string>, decltype( less )> s( less );
73,101,924
73,102,126
Assign pointer to 2d array to an array
So I got a function which creates me 2D array and fill it with test data. Now I need to assign the pointer to an array //Fill matrix with test data int *testArrData(int m, int n){ int arr[n][m]; int* ptr; ptr = &arr[0][0]; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ *((ptr+i*n)+j) = rand()%10; } } return (int *) arr; } int arr[m][n]; //Algorithm - transpose for (int i = 0; i < m; i++){ for (int j = 0; j < n; j++){ arrT[j][i] = arr[i][j]; } } Is there any way of doing this?
There are at least four problems with the function. //Fill matrix with test data int *testArrData(int m, int n){ int arr[n][m]; int* ptr; ptr = &arr[0][0]; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ *((ptr+i*n)+j) = rand()%10; } } return (int *) arr; } First of all you declared a variable length array int arr[n][m]; Variable length arrays are not a standard C++ feature. The second problem is that these for loops for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ *((ptr+i*n)+j) = rand()%10; } } are incorrect. It seems you mean for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ *((ptr+i*m)+j) = rand()%10; } } You are returning a pointer to a local array with automatic storage duration that will not be alive after exiting the function. So the returned pointer will be invalid. And arrays do not have the assignment operator. Instead use the vector std::vector<std::vector<int>>. For example std::vector<std::vector<int>> testArrData(int m, int n){ std::vector<std::vector<int>> v( n, std::vector<int>( m ) ); for ( auto &row : v ) { for ( auto &item : row ) { item = rand() % 10; } } return v; }
73,101,942
73,109,073
Constexpr function evaluation on a template parameter object (MSVC vs clang/gcc)
As I understand it, the following should be valid C++20: template<int i> struct A {}; struct B { constexpr int one() const { return 1; } }; template<B b> A<b.one()> f() { return {}; } void test() { f<B{}>(); } MSVC does not like this (Visual Studio 2022, but godbolt appears to show all versions failing in some way, including an ICE for v19.28): error C2672: 'f': no matching overloaded function found error C2770: invalid explicit template argument(s) for 'A<'function'> f(void)' Both clang and gcc accept it though. As a workaround, wrapping the function evaluation works fine: template<B b> struct WrapOne { static constexpr int value = b.one(); }; template<B b> A<WrapOne<b>::value> f() { return {}; } Wrapping via an inline constexpr variable also works: template<B b> inline constexpr auto one_v = b.one(); template<B b> A<one_v<b>> f() { return {}; } I'm assuming that this is a bug in MSVC? I couldn't find anything relevant on the MS Developer Community site, but it feels like a pretty fundamental thing that other people must have come across. Any other clever workarounds?
Yes, seems like a bug to me as well. The parser seems to have a problem specifically with the member function call via . in the template argument. It works when using ->: template<B b> A<(&b)->one()> f() { return {}; }
73,101,971
73,109,045
Why voltage from Raspberry Pi Pico ADC is not equal 0, when nothing is connected to the pin?
I was trying to read some voltages from a sensor, but before doing that, I checked how readings would look like, when nothing is connected to pins. Here's my code based on examples: #include <stdio.h> #include "pico/stdlib.h" #include "hardware/gpio.h" #include "hardware/adc.h" int main() { stdio_init_all(); const float conversion_factor = 3.3f / (1 << 12); adc_init(); gpio_set_dir_all_bits(0); for (int i = 2; i < 30; ++i) { gpio_set_function(i, GPIO_FUNC_SIO); if (i >= 26) { gpio_disable_pulls(i); gpio_set_input_enabled(i, false); } } gpio_init(PICO_DEFAULT_LED_PIN); gpio_set_dir(PICO_DEFAULT_LED_PIN, GPIO_OUT); adc_set_temp_sensor_enabled(true); bool enabled = 0; while (1) { float result[3]; for (int i=0; i<3; i++) { adc_select_input(i); sleep_ms(10); result[i] = adc_read() * conversion_factor; } adc_select_input(4); sleep_ms(10); float temp_adc = (float)adc_read() * conversion_factor; float tempC = 27.0f - (temp_adc - 0.706f) / 0.001721f; printf("Voltage 0-2: %f,%f,%f V, temp: %f\r\n", result[0], result[1], result[2], tempC); enabled = (enabled + 1) % 2; gpio_put(PICO_DEFAULT_LED_PIN, enabled); sleep_ms(2000); } } I got the output in which only onboard temperature seems reasonable and not changing: Voltage 0-2: 1.145654,0.374634,1.025610 V, temp: 23.861492 Voltage 0-2: 0.407666,1.086035,0.441504 V, temp: 23.393347 Voltage 0-2: 1.136792,0.359326,1.046558 V, temp: 23.393347 Voltage 0-2: 0.558325,0.605859,0.579272 V, temp: 23.861492 Voltage 0-2: 0.645337,0.504346,0.696094 V, temp: 23.861492 In addition, I have two Raspberry Pi Pico's, and got similar result's on both. Why values from ADC 0 to 2 are not equal/near 0, and they're changing so rapidly, when completely nothing is connected to the Pico?
Pins are never not connected. They have a pullup/down resistor that can be switched on or off and they are connected to the read and write circuitry that can be switched between. Those aren't physical switches. When you switch the pullup/down resistor off what that really means is that you make that a really high resistor. A bit of current will always leak across the switch. You also have current running through nearby pins that might induce a current in the floating pin. You might also simply have residual charge left on the pin from when it was connected or was an output pin. If a floating pin was output HIGH and you switch it to read the next value you read is probably going to be HIGH. Reading that drains a bit of the left over charge so if you wait a bit the next read might be LOW. Measuring a floating pin is basically meaningless but might be a source for random bits. For anything else that's what the pullup/down resistors are for. [If the Pico doens't have those you have to connect one externally].
73,102,119
73,102,127
How to inherit constructors? OR how to make similar constructors?
I am making a class for a character with several attributes. I made it so the user has to choose between 3 objects made from the constructor of that first class. I cant think of a way to choose between the objects so I want to create a class that inherits the attributes of the first class(basically a copycat) but will only copy the chosen object. #include <iostream> #include <cmath> #include <windows.h> using namespace std; class Character { public: string weapon; float HP; float MP; float str; float def; Character(string aweapon, float aHP, float aMP, float astr, float adef){ weapon = aweapon; HP = aHP; MP = aMP; str = astr; def = adef; } }; class Chose : public Character{ }; int main() { Character warrior("sword", 100, 20, 50, 50); Character tank("shield", 200, 20, 25, 80); Character magician("staff", 80, 100, 30, 30); Chose that; // error is here cout << warrior.HP << endl; return 0; } error says:- |24|error: no matching function for call to 'Character::Character()' |15|candidates are: |15|note: Character::Character(std::string, float, float, float, float) |15|note: candidate expects 5 arguments, 0 provided |7|note: Character::Character(const Character&) |7|note: candidate expects 1 argument, 0 provided |39|note: synthesized method 'Chose::Chose()' first required here Sooooo, I can't figure out the problem here.
class Chose : public Character{ public: using Character::Character; }; https://godbolt.org/z/TEG7Pvdxa Note that you are trying use default constructor of Character which was removed since custom constructor was defined. As result default constructor of Chose can't be created implicitly (since base class do not have default constructor).
73,102,933
73,102,959
member function of an object of class map
I somehow not sure what is wrong with call to insert for the object "history" where history is of type map. I have checked that there should be an insert function for a map object where the insert function would take in a pair as an argument. However I keep getting the error of #include <map> using namespace std; class Solution { public: ListNode *detectCycle(ListNode *head) { std::map<ListNode, int> history; \\ so here history is created to be an object of type map ListNode *current = head; if(head == NULL) { return nullptr; } else { while(current->next) { history.insert(make_pair(current, current->val)); \\ this line has the error of no matching member function for call to "insert" if(history.count(current->next)) { return current->next; } } } return nullptr; } }; could someone points out what is wrong here? or maybe my understanding in the c++ map class? sorry I am pretty new to c++ and my uses of c++ terminology might not even be right. thank you
std::map<ListNode, int> history; This map's key is a ListNode. ListNode *current = head; current is a ListNode *, a pointer to a ListNode. history.insert(make_pair(current, current->val)); This attempts to insert a ListNode * key into a map whose key is a ListNode. This is ill-formed. If a map's key is an int, an inserted key must be an int. If the map's key is a ListNode the inserted key must be a ListNode. If the map's key is a ListNode * the inserted key must be a ListNode *. Either your map's key is wrong, or your insert() call is wrong. P.S. You appear to be using an outdated C++ textbook to learn C++, or an old C++ compiler that does not implement the current C++ standard. Modern C++ uses a cleaner "uniform initialization" syntax with insert() instead of std::make_pair. You should see if you can find a more recent textbook and/or compiler, that support modern C++.
73,103,121
73,103,373
If statement only works once
Here is my code: #include <FastLED.h> #define LED_PIN 7 #define NUM_LEDS 20 CRGB leds[NUM_LEDS]; void setup() { pinMode(A0, INPUT_PULLUP); FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS); } void loop() { if (digitalRead(A0) == HIGH) { TEST (); } } void TEST() { leds[0] = CRGB(255, 0, 0); FastLED.show(); delay(500); leds[1] = CRGB(0, 255, 0); FastLED.show(); delay(500); leds[2] = CRGB(0, 0, 255); FastLED.show(); delay(500); leds[3] = CRGB(150, 0, 255); FastLED.show(); delay(500); leds[4] = CRGB(255, 200, 20); FastLED.show(); delay(500); leds[5] = CRGB(85, 60, 180); FastLED.show(); delay(500); leds[6] = CRGB(50, 255, 20); FastLED.show(); } Here's what I'm stuck on: The code is supposed to detect voltage on the A0 pin, ad trigger my test function to make the LEDs glow sequentially. My current issue is that it works, but only once. If I remove the voltage and retry it, the function does not execute. I'm not really sure what I am doing wrong. My end goal is to create code for sequential taillights for my car, this is just a proof of concept. Basically what I want to happen is for the Arduino to detect the voltage from the car's signal and create a sequential animation. I know for that to work I can't use the delay function, but I cat figure out how to make a timer that I can reset to zero. So any help with that issue would also be appreciated. Sorry if this is worded poorly or a simple solution, I am new to arduino.
According to the rule of writing code, the description of the called function should be higher than the place of its call. I mean that the TEST() function should be between setup() and loop() You need to turn off the LEDs after they have been turned on, this can be achieved with specific function from the FastLED library or as follows: void loop() { for(size_t i = 0; i != 7; ++i) { leds[i] = CRGB(0, 0, 0); } // your code } It is not necessary to compare the digital result with the HIGH signal value. If the value from the sensor is HIGH, then this is automatically converted to 1, which is true in the programming language and the condition is met. If the signal is LOW, then 0 is false and the condition is not met. You can simply write it like this: if (digitalRead(A0)) { TEST (); } Also, make sure what signal the sensor produces. I see that in the pinMode(pin, mode) function you have connected the sensor to an analog pin that has a range of values ​​from 0 to 1023, but in the condition you are reading a digital signal with values ​​of 0 or 1. You use the work mode in INPUT_PULLUP mode in pinMode(), it works in reverse. For example, if the button is pressed, then it gives a LOW signal, and if it is not pressed, then a HIGH one. If you need ordinary logic, then you should use the INPUT mode. But it all depends on your connection, and you can not get hung up on this. It is desirable to connect digital sensors to digital pins, and analog sensors to analog ones. Moreover, if you have an analog sensor, then you do NOT need to write a pinMode(). Thus, if your analog signal outputs a value of 0, then it will be LOW for digital, and all other values ​​are converted to a HIGH signal. It would be more correct to read the analog signal with the analogRead() function. Voltage-free analog signals can produce some kind of signal, so it's worth taking this into account in your program. It is necessary to measure a certain threshold after which your function should work, for example, if in a calm state the signal is not higher than 20-30, then you can write the condition as follows: if (analogRead(A0) > 50) { TEST (); } Also note that you have delays in the function and during this time the voltage may drop, and the condition will not work the next time. You can use a boolean variable that will capture the voltage and convert the value to true or false. Or you can use a counter. Code: #include <FastLED.h> #define LED_PIN 7 #define NUM_LEDS 20 CRGB leds[NUM_LEDS]; void setup() { // if you have an analog sensor, then you do NOT need to write a pinMode() pinMode(A0, INPUT_PULLUP); // maybe INPUT_PULLUP -> INPUT FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS); } void TEST() { leds[0] = CRGB(255, 0, 0); FastLED.show(); delay(500); leds[1] = CRGB(0, 255, 0); FastLED.show(); delay(500); leds[2] = CRGB(0, 0, 255); FastLED.show(); delay(500); leds[3] = CRGB(150, 0, 255); FastLED.show(); delay(500); leds[4] = CRGB(255, 200, 20); FastLED.show(); delay(500); leds[5] = CRGB(85, 60, 180); FastLED.show(); delay(500); leds[6] = CRGB(50, 255, 20); FastLED.show(); } void loop() { // turn off the LEDs for(size_t i = 0; i != 7; ++i) { leds[i] = CRGB(0, 0, 0); } // make sure what signal the sensor produces if (analogRead(A0)) { TEST (); } }
73,103,528
73,103,618
cLion C++ "Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)"
Just started using cLion as an ide for c++. Am attempting to run this block of code where it reads a csv file and stores the values in a 189 x 141 2d vector. It then iterates through 5 for loops. Everything was running smoothly until I included the 5 nested for loops; at this point I was seeing the "Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)" message upon executing. I have seen an answer to a similar question claiming that it is the result of a lack of memory on my computer. Would this be the case? When the first 3 for loops have ib0, ib1, ib2 iterate from 0 to 100, it would of course mean that there are over 26 billion iterations in total. However, when I reduce this range to 0 to 1, I still receive the message. For reproducibility, I just have the ROB vector be 189 x 141 random values. EDIT: If anyone runs this code, let me know how long it takes? #include <iostream> #include <vector> #include <cmath> using namespace std; int main() { double innerarrayval; vector<vector<double>> ROB; vector<double> innerarray; for(int x=0;x<189;x++) { innerarray.clear(); for (int y = 0; y < 141; y++) { innerarrayval = rand() % 1000; innerarray.push_back(innerarrayval); } ROB.push_back(innerarray); } double b0,b1,b2; int nnb; double chisquared, amean, content, sumpart, sumpartsquared,chisquaredNDOF,chimin; double b0mem, b1mem, b2mem; chimin = 1000.0; for(int ib0 = 0; ib0 < 101; ib0++) { b0 = 15.0 + 0.1 * (ib0 - 1); for(int ib1 = 0; ib1 < 101; ib1++) { b1 = -0.002 * (ib1 - 1); for(int ib2 = 0; ib2 < 101; ib2++) { b2 = 0.002 * (ib2 - 1); nnb = 0; chisquared = 0; amean = 0; for(int i = 0; i <= 189; i++) { for(int j = 0; j <= 141; j++) { if((i >= 50 and i <= 116) and (j >= 42 and j <= 112)) { continue; } else { content = ROB[i][j]; if(content == 0) { content = 1; } amean = amean + content; sumpart = (content - b0 - (b1 * i) - (b2 * j))/sqrt(content); sumpartsquared = pow(sumpart, 2); chisquared = chisquared + sumpartsquared; nnb = nnb + 1; } } } chisquaredNDOF = chisquared/double(nnb); amean = amean/double(nnb); if(chisquaredNDOF < chimin) { chimin = chisquaredNDOF; b0mem = b0; b1mem = b1; b2mem = b2; } } } } cout<<"chi squared: "<<chimin<<"\n"; cout<<"b0: "<<b0mem<<"\n"; cout<<"b1: "<<b1mem<<"\n"; cout<<"b2: "<<b2mem<<"\n"; cout<<"mean: "<<amean<<"\n"; return 0; }
for(int x=0;x<189;x++) { innerarray.clear(); for (int y = 0; y < 141; y++) { innerarrayval = rand() % 1000; innerarray.push_back(innerarrayval); } ROB.push_back(innerarray); } This part of the initialization loops carefully, and gingerly, initialized the two-dimensional ROB vector. As noted by each for loop's limit, the valid indexes for the first dimension is 0-188, and the 2nd dimension is 0-140. This is correct. In C++ array/vector indexes start with 0, so for your expected result of a "189 x 141 2d vector", the first index's values range 0-188, and the 2nd one's range is 0-140. If you proceed further in your code, to the part that reads the two-dimensional matrix: for(int i = 0; i <= 189; i++) { for(int j = 0; j <= 141; j++) { And because this uses <=, this will attempt to access values in ROB whose first dimension's index range is 0-189 and the 2nd dimension's index range is 0-141. The out of bounds access results in undefined behavior, and your likely crash. You should use this obvious bug as an excellent opportunity for you to learn how to use your debugger. If you used your debugger to run this program, the debugger would've stopped at the point of the crash. If you then used your debugger to inspect the values of all variables, I would expect that the out-of-range values for i or j would be very visible, making the bug clear.
73,103,639
73,103,677
How do I align my output when a word is too long?
I am trying to create a program where the user enters 5 candidates for an election along with their number of votes. The program's output creates a table where it shows each candidates name, their votes, percentage of votes, and the winner of the election. My code is below and a sample of the output is in a picture that I have uploaded. #include <iostream> #include <string> #include <fstream> #include <iomanip> #include <conio.h> using namespace std; const int numofcandidates = 5; // declare variables and arrays string candidateName[numofcandidates] = { "" }; int candidatevotes[numofcandidates]; float totalvotepercentage; // declare methods void takeNameandVote(); void printTable(); int main() { takeNameandVote(); printTable(); } void takeNameandVote() { for (int i = 0; i < numofcandidates; i++) { cout << "Enter last name for candidate " << i + 1 << ": "; cin >> candidateName[i]; cout << "Enter number of votes for this candidate: "; cin >> candidatevotes[i]; } } void printTable() { // to set up % of total votes int totalvotes = 0; for (int i = 0; i < numofcandidates; i++) { totalvotes += candidatevotes[i]; } cout << "Candidate\tVotes Received\t\t" << '%' << " of Total Votes" << endl; for (int i = 0; i < numofcandidates; i++) { cout << candidateName[i] << '\t' << setw(18) << candidatevotes[i] << "\t" << fixed << showpoint << setprecision(2) << setw(16) << (candidatevotes[i] / (double)totalvotes * 100) << endl; } cout << "Total\t\t" << setw(10) << totalvotes << endl; cout << endl; }
Remove all \ts and only use std::setw: std::cout << std::left << std::setw(18) << candidateName[i] << std::right << std::setw(8) << candidatevotes[i] << ...
73,103,713
73,103,807
why there is error when i use the overload
i'm using boost::asio, i want to know why there is error when i use different overload; ``` #include<boost/asio.hpp> using namespace boost::asio; int main(int argc,char* argv[]){ io_service ios; ip::tcp::acceptor acc(ios); } ``` it can run when i use the command"g++ -o server server.cpp -lboost_system -lboost_thread -lpthread" there is another situation: ``` #include<boost/asio.hpp> using namespace boost::asio; int main(int argc,char* argv[]){ io_service ios(); ip::tcp::acceptor acc(ios); } ``` it cant run and there is the errorinfo: In file included from /usr/include/boost/asio/executor.hpp:338, from /usr/include/boost/asio/basic_socket.hpp:27, from /usr/include/boost/asio/basic_datagram_socket.hpp:20, from /usr/include/boost/asio.hpp:24, from server.cpp:1: /usr/include/boost/asio/impl/executor.hpp: In instantiation of ‘boost::asio::execution_context& boost::asio::executor::impl< <template-parameter-1-1>, <template-parameter-1-2> >::context() [with Executor = boost::asio::io_context (*)(); Allocator = std::allocator<void>]’: /usr/include/boost/asio/impl/executor.hpp:177:22: required from here /usr/include/boost/asio/impl/executor.hpp:179:22: error: request for member ‘context’ in ‘((boost::asio::executor::impl<boost::asio::io_context (*)(), std::allocator<void> >*)this)->boost::asio::executor::impl<boost::asio::io_context (*)(), std::allocator<void> >::executor_’, which is of non-class type ‘boost::asio::io_context (*)()’ 179 | return executor_.context(); | ~~~~~~~~~~^~~~~~~
io_service ios(); This declares a function called ios returning io_service. This is known as the "Most Vexing Parse". Either use {} instead of () (since C++11) or just leave the parentheses.
73,103,833
73,104,117
Boost Karma for a boost::variant containing a custom class
I'd like to investigate boost::spirit::karma::generate as a replacement for std::stringstream for a boost::variant containing, apart from familiar types such as int and double, one or more custom classes (e.g. A). However I'm unable to even compile the code once I include one or more custom classes in the variant. #include <iostream> #include <boost/spirit/include/karma.hpp> #include <boost/variant.hpp> struct A { double d; explicit A(const double d) : d(d) {} friend std::ostream& operator<<(std::ostream& os, A const& m) { return os << "{" << m.d << "}"; } }; BOOST_FUSION_ADAPT_STRUCT(A, d) using Variant = boost::variant<int, double, A>; void test_stringstream(const Variant &v) { std::stringstream os; os << v; std::cout << os.str() << std::endl; } void test_karma(const Variant &v) { std::string str; boost::spirit::karma::generate(std::back_inserter(str), v); std::cout << str << std::endl; } int main() { A a(double(1.0)); std::cout << a << std::endl; test_stringstream(Variant(a)); test_karma(Variant(a)); } I'd expect the output: {1} {1} {1} The error output begins with mpl_iterator.hpp:45:24: error: no matching constructor for initialization of 'boost::fusion::mpl_iterator<boost::mpl::l_iter<boost::mpl::l_item<mpl_::long_<1>, A, boost::mpl::l_end>>>::deref<boost::fusion::mpl_iterator<boost::mpl::l_iter<boost::mpl::l_item<mpl_::long_<1>, A, boost::mpl::l_end>>>>::type' (aka 'A') return type(); Apart from custom classes, I'd also like to enquire how one could make Enums 'streamable' as it were via boost::spirit::karma::generate.
The error message informs you that A is not default-constructible. It's a long type expression, but helpfully summarized it for you: (aka 'A'). Adding a default value for d fixes it: explicit A(double d = {}) : d(d) {} Now with std::cout << "iostream: " << a << std::endl; std::cout << "stringstream: "; test_stringstream(Variant(a)); std::cout << "karma: "; test_karma(Variant(a)); You'd see (Live) iostream: {1} stringstream: {1} karma: You didn't pass any karma expression to generate. Let's add: void test_karma(const Variant& v) { namespace k = boost::spirit::karma; std::string str; k::generate(std::back_inserter(str), k::stream, v); std::cout << str << std::endl; } Now you get the same output. Note that the Fusion adaptation is completely unnecessary here, don't actually ever deal with A in your karma expression. It will effectively amount to the stringstream implementation, but with extra steps, so it will be slower. Demo Live Prints iostream: {1} stringstream: {1} karma: {1} Suggestions I'd suggest using Boost lexical_cast here. It's almost guaranteed to be faster and certainly less ... clumsy: Live On Coliru #include <boost/lexical_cast.hpp> #include <boost/variant.hpp> #include <iostream> struct A { explicit A(double d = {}) : d(d) {} private: double d; friend std::ostream& operator<<(std::ostream& os, A const& m) { return os << "{" << m.d << "}"; } }; using Variant = boost::variant<int, double, A>; int main() { Variant vv[]{42, 3.14, A(1.0)}; for (Variant a : vv) std::cout << boost::lexical_cast<std::string>(a) << "\n"; } Prints 42 3.14 {1}
73,103,972
73,120,142
multi-dimensional array type as template argument
The kokkos scientific computing library implements the multi-dimensional array (which they call View) such that it knows which dimensions are fixed at compile time and which dimensions are runtime variable. For example, to create a 3-dimensional array data of shape (N0, N1, N2), you can do one of the followings: View<double***> data(N0, N1, N2); // 3 run, 0 compile View<double**[N2]> data(N0, N1); // 2 run, 1 compile View<double*[N1][N2]> data(N0); // 1 run, 2 compile View<double[N0][N1][N2]> data(); // 0 run, 3 compile If I want to implement something like View, how should I handle the the template arguments? i.e. How should I count number of asterisks and square brackets (and get the numbers in those square brackets) of the template argument in my implementation?
This question can be split into two parts. Get the dimensions from the input template parameter T. Constructor accepts different numbers of values as run-time dimensions. Let's look at it one by one. To solve the first problem, a non-type typelist is used to represent the dimensions. template <size_t... Ns> struct Dimension { template <size_t N> using prepend = Dimension<N, Ns...>; }; 0 means the dimension is determined at run-time. Now we construct a template class hoping to decompose its template parameter into the dimensions we want. template <typename> struct Analysis; // Analysis<int**> -> Dimension<0, 0> // Analysis<int[1][2] -> Dimension<1, 2> // Analysis<int*[3]> -> Dimension<0, 3> Using alias template nested inside specialization to decompose the pointers / [] layer by layer recursively. Compile-time dimensions and run-time dimensions are represented separately and joined together. Whenever meeting a *, prepend a 0 in the dynamic dimension. Whenever meeting a [N], prepend an N in the static dimension. template <typename T> struct Analysis { using sdim = Dimension<>; // static using ddim = Dimension<>; // dynamic using dim = Dimension<>; // all }; template <typename T, size_t N> struct Analysis<T[N]> { using nested = Analysis<T>; using sdim = typename nested::sdim::template prepend<N>; using ddim = typename nested::ddim; using dim = join_t<ddim, sdim>; }; template <typename T> struct Analysis<T*> { using nested = Analysis<T>; using sdim = typename nested::sdim; using ddim = typename nested::ddim::template prepend<0>; using dim = join_t<ddim, sdim>; }; T[] is similar to T*, not shown here. Now we have, static_assert(std::is_same_v< Analysis<int[1][2][3]>::dim, Dimension<1, 2, 3>>); static_assert(std::is_same_v< Analysis<int***>::dim, Dimension<0, 0, 0>>); static_assert(std::is_same_v< Analysis<int*[1][2]>::dim, Dimension<0, 1, 2>>); Demo Since we've got the dimensions, constructing a View-like thing is simple. Its constructor accepts a bunch of parameters with a default value as run-time dimensions. template <typename T> struct View { using dim = typename Analysis<T>::dim; View(size_t dim0 = -1, size_t dim1 = -1, size_t dim2 = -1) { // you could write more if (get_v<dim, 0> == 0 && dim0 != -1) { // run-time } if (get_v<dim, 1> == 0 && dim1 != -1) {} if (get_v<dim, 2> == 0 && dim2 != -1) {} } }; Demo
73,104,095
73,104,135
Are DLLs generally non-ideal for speed critical applications?
Up until now, I've only ever written and built static libraries, and so, I'm new to the shared library scene, or DLLs, as they are called on Windows. From what I understand, the key feature of DLLs is that the library code is "loaded" and "unloaded" from the application as it makes calls into library. As such, my question is, does this dynamic loading and unloading (generally) make DLLs non-ideal for speed critical applications? For example, consider this C++ snippet: int x = 4; lib_function(x); non_lib_function(); My_Lib_Type foo(4, 3); Assuming My_Lib_Type and lib_function() are defined in the DLL, would the application load the library to call lib_function(), unload after the call, and then load again to call the constructor for My_Lib_Type? If this is how it works, how fast is this switching process?
A DLL is typically loaded (and unloaded) only once by an application: either implicitly (if your executable is linked against it, via the corresponding export library) or explicitly (via calls to LoadLibrary() and FreeLibrary(), on Windows). It is not loaded each time one of its functions is called. Once that DLL is loaded, its component functions and other exported units are accessed in much the same way as those defined in the executable module itself – the DLL is loaded into the process memory of the calling application. So, no, there will be no noticeable speed degradation (or there shouldn't be) when using a DLL over a statically-linked library.
73,104,139
73,105,411
Resolving the issue of unsafe function deprecation and misusing time-getting methods like std::ctime() or std::localtime() to get local time in C++
I'm building a simple small program for fun, to kill time and learn something. I simply want my program to display local time (I live in Buffalo, NY, so I'm in ET). I put together an ostensibly ridiculous soup of libraries to ensure that my program is aware of everything: #include <iostream> #include <chrono> #include <ctime> #include <cstdlib> #ifdef __unix__ # include <unistd.h> #elif defined _WIN32 # include <windows.h> #define sleep(x) Sleep(1000 * (x)) #endif I tried the code from this page that uses the localtime() method: #include <ctime> #include <iostream> int main() { std::time_t t = std::time(0); // get time now std::tm* now = std::localtime(&t); std::cout << (now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-' << now->tm_mday << "\n"; } I also tried a chunk of code that uses the ctime() method from here > How to get current time and date in C++? : #include <iostream> #include <chrono> #include <ctime> int main() { auto start = std::chrono::system_clock::now(); // Some computation here auto end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; std::time_t end_time = std::chrono::system_clock::to_time_t(end); std::cout << "finished computation at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << "s" << << std::endl; } Every time I try something, my efforts are accompanied with the compiler stating the following: Error C4996 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. 15Puzzle C:\Users\owner\source\repos\15Puzzle\main.cpp 10 ... and when I follow that suggestion, the compiler states that the std library does not have the recommended method. I really don't want to disable anything cautionary. What should I do?
(Ideas for the answer were contributed by Adrian Mole and n. 1.8e9-where's-my-share m. in the comments to the OP question.) The C4996 is simply a stumbling block designed by Microsoft. To bypass this "error", simply set the _CRT_SECURE_NO_WARNINGS flag to true by adding the following to the very top of the main file: #define _CRT_SECURE_NO_WARNINGS 1 There seems to be more than one theory as to why Microsoft would do this, but the truth is that there's really nothing wrong with using the chrono library's traditional functions.
73,104,194
73,104,251
String converted to Array. Modulo the value is incorrect
char* array{}; string digit4; cout << "Enter a 4 digit-integer : " << endl; cin >> digit4; cout << "The 4 digit-integer you have entered is : " << digit4 << endl; array = &digit4[0]; cout << "Digit 1 is : " << array[0] << endl; int digit1 = (array[0] + 7) % 10; cout << digit1 << endl; return I tried to convert a string to an array and use the first digit of array[0] to a formula of ( array[0] + 7 ) % 10. If I input 1234, ( 1 + 7 ) % 10 should be 8 but I'm getting 6 instead of 8. Any help would be great. Thank you for reading.
The expression array[0] evaluates to the character code for the digit '1', which is 49 in ASCII. Therefore, assuming that you are using ASCII, the expression (array[0] + 7) % 10; is equivalent to (49 + 7) % 10 which is 6. If you want to get the value that is represented by the digit, then you can simply subtract '0' (which is the character code for the digit '0', which is 48 in ASCII) from the character code of the digit. Therefore, to solve your problem, you can simply change the line int digit1 = (array[0] + 7) % 10; to: int digit1 = ( array[0] - '0' + 7 ) % 10;
73,104,401
73,104,931
Using QHttpMultiPart with PUT operation and form fields
I'm having quite a bit of struggle in trying to achieve a simple PUT request in QT. Frankly I am still a starter using this framework so I have much left to learn. What I am trying to do is make a PUT request with 2 parameters this Cloudflare Workers KV API. With that being said this is my current code snippet: QString szUrl = ""; QHttpMultiPart* multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart valuePart; valuePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"value\"")); valuePart.setBody(value.toByteArray()); QHttpPart metadataPart; metadataPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"metadata\"")); metadataPart.setBody(metadata.toByteArray()); multiPart->append(valuePart); multiPart->append(metadataPart); QNetworkRequest request; request.setUrl(szUrl); request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data"); request.setRawHeader("Authorization", QString("Bearer %1").arg("...").toUtf8()); QNetworkReply* reply = m_NetworkManager->put(request, multiPart); // delete the multiPart with the reply multiPart->setParent(reply); // Process reply (QNetworkAccessManager::finished) // Process errors (QNetworkAccessManager::sslErrors) qDebug() << reply->error(); qDebug() << reply->readAll(); qDebug() << reply->errorString(); The above returns always HTTP 400 (bad request) with zero, and I mean ZERO response. I could not retrieve the error response from the API in any way. Just an empty string ("") under debug. If I execute the example cURL cli code from the API page, it works perfectly. I get a response and it's successful. My question would be, what on earth am I doing wrong? I read the documentation and wrote the code accordingly, I cannot understand what's happening. I have searched quite a bit for a possible answer online but unfortunately all issues and examples are with POST requests and file uploads (mostly). Please advise, it would be much appreciated.
I will answer my own question because one of the reasons the above was not working it's because of my own fault. Problem 1: Bad formatting of metadata. Looks like Cloudflare API wants the metadata "compressed". Problem 2: Unable to retrieve API error response. Now this is an interesting one because I found countless forum posts and posts even here with the same problem, yet nobody posted the actual solution. The readAll() function states this issue: This function has no way of reporting errors; returning an empty QByteArray can mean either that no data was currently available for reading, or that an error occurred. This function also has no way of indicating that more data may have been available and couldn't be read. The resolution is to connect QIODevice::readyRead to as per the documentation: connect(reply, &QIODevice::readyRead, this, [=]() { QByteArray response = reply->readAll(); qDebug() << response; }); You now have the server reply regardless of the HTTP error code. With that being said 2 problems solved in one go, enjoy.
73,104,516
73,104,746
How to make a template cycle?
I'm very often fiddling with cycle and they're almost the same, I think you can simplify a lot of code if you have one template. // the blocks can be different, but the number is known before compilation const int block_1 = 10, block_2 = 4, block_3 = 6, block_4 = 3; Basically all cycles are like this the cycle can be like this for (int i = 1; i < block_1 - 1; ++i) { } or this for (int i = 1; i < block_1 - 1; ++i) { for (int k = 1; k < block_2 - 1; ++k) { } } or this for (int i = 1; i < block_1 - 1; ++i) { for (int k = 1; k < block_2 - 1; ++k) { for (int j = 1; j < block_3 - 1; ++j) { } } } The number of cycle within a cycle can be a lot, but they are similar. I think that if I use a template instead of loops all the time, would it be more convenient or not, but maybe I shouldn't and you will dissuade me from doing it. Ideally I would like a template like this for_funk(block_1, block_2, block_3) { // Here I write the code that will be inside the three loops block_1, block_2, block_3 } Maybe this will help https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2374r4.html
Yes, you can compose iota_view and cartesian_product_view to get nested indexes in C++23 constexpr inline auto for_funk = [](auto... index) { return std::views::cartesian_product(std::views::iota(1, index-1)...); }; const int block_1 = 10, block_2 = 4, block_3 = 6, block_4 = 3; for (auto [i, j, k, w] : for_funk(block_1, block_2, block_3, block_4)) // use i, j, k, w Demo with range-v3
73,104,673
73,104,775
Interpreting the & sign in C++
My confusion: Since both the pointers and references use the symbol &, and in pointers & symbol is usually interpreted as "the address of ...", I wonder whether it should be interpreted the same in references. My theory: When & sign appears on the right hand side of =, it can be interpreted as "the address of". When & sign appears on the left hand side of =, it should be associated with references and CAN'T be directly interpreted as "the address of". My proof: & in pointers: int a = 1; int *p = &a; The value of pointer variable p is the address of variable a. In other words, p is a pointer pointing to variable a. & in references: int a = 1; int & b = a; b is a reference to a. In other words, the address of reference variable b is the same as the address of variable a. But the code itself wouldn't be appropriate to directly interpreted it as "the address of reference variable b is the address of variable a", because otherwise then the code should instead be int a = 1; int & b = &a; , and that is incorrect according to C++ syntax. Error message: error: cannot bind rvalue '(int)(& a)' to 'int&' Thanks for replies in advance!
Since there are only so many ASCII symbols, it's inevitable that they get re-used for contradictory purposes, and & is one such character. It means either address of in a statement or reference to in a variable declaration. Thinking of the "right-hand-side" is close, but it's really just its presence in a statement or, more specifically, an expression. Remember the rules apply in function definitions as well, as in int f(int &a) where there's no RHS in play. In your example: int & b = a; This reads as "b is a reference to a, which is an int". Keep in mind references might seem similar to addresses as in pointers, but they are not at all the same. A reference is an alias, as in it is entirely equivalent to. A pointer is, by definition, always one degree removed. That is in the case of: b = 2; This assigns directly to b, which is an alias for a, so they both change. To adjust a pointer int *c = &a you would need to do *c = 2 which changes a but does not change c, the address of a remains the same. Remember you can have references to pointers, pointers to references, and any combination you can dream up, even from nightmares, like int &*&**&***a if you so wish. It's valid! (Just not recommended.) So things to keep in mind for a simple example of int &b = a: b and a share the same address Modifying b always modifies a To the compiler, b is just an alias for a b[0] is a syntax error unless a can be indexed as an array *b is a syntax error unless a can be de-referenced as pointer Whereas for int *c = a: c has a different address from a c is a different variable from a Modifying c directly does not modify a Modifying a de-referenced *c does modify a c behaves like an array, as in c[0] can be used to fetch or modify a Pointers generally incur an additional level of overhead when de-referencing and "exercising" them If you're ever wondering what's going on, look at the assembly output of a simple program that uses both pointers and references. The differences can be substantial.
73,104,949
73,113,348
Any metrics could measure vignetting effect of images?
I would like to detect the pictures suffered by Vignetting or not, but cannot find a way to measure it. I search by keywords like "Vignetting metrics, Vignetting detection, Vignetting classification", they all lead me to topics like "Create vignetting filters" or "Vignetting correction". Any metric could do that? Like score from 0 to 1, the lower the score, the more unlikely the images suffered from vignetting effect. One of the naive solution I come up is measure the Luminance channel of the image. #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> using namespace cv; using namespace std; int main() { auto img = imread("my_pic.jpg"); cvtcolor(img, img, cv::COLOR_BGR2LAB); vector<Mat> lab_img; split(img, lab_img); auto const sum_val = sum(lab_img[0])[0] / lab_img[0].total(); //use sum_val as threshold } Another solution is trained a classifier by CNN, I could use the vignetting filter to generate images with/without vignetting effect. Please give me some suggestions, thanks.
Use a polar warp and some simple statistics on the picture. You'll get a plot of the radial intensities. You'll see the characteristic attenuation of a vignette, but also picture content. This 1D signal is easier to analyze than the entire picture. This is not guaranteed to always work. I'm not saying it should. It's an approach. Variations are conceivable that use medians, averages, ... but then you'd have to introduce a mask too, so you know what pixels are coming from the image and which ones are just out-of-bounds black (to be ignored). You can extend the source image to 4-channel, with the fourth channel being all-255. The warp will treat that as any other color channel, so you'll get a "valid"-mask out of it that you can use. I am confronting you with Python because it's about the idea and the APIs, and I categorically refuse to do prototyping/research in C++. (h,w) = im.shape[:2] im = np.dstack([im, np.full((h,w), 255, dtype=np.uint8)]) # 4th channel will be "valid mask" rmax = np.hypot(h, w) / 2 (cx, cy) = (w-1) / 2, (h-1) / 2 # dsize dh = 360 * 2 dw = 1000 # need to explicitly initialize that because the warp does NOT initialize out-of-bounds pixels warped = np.zeros((dh, dw, 4), dtype=np.uint8) cv.warpPolar(dst=warped, src=im, dsize=(dw, dh), center=(cx,cy), maxRadius=int(rmax), flags=cv.INTER_LANCZOS4) values = warped[..., 0:3] mask = warped[..., 3] values = cv.cvtColor(values, cv.COLOR_BGR2GRAY) picture 1: picture 2: mvalues = np.ma.masked_array(values, mask=(mask == 0)) # numpy only has min/max/median for masked arrays # need this for quantile/percentile # this selects the valid pixels for every column cols = (col.compressed() for col in mvalues.T) cols = [col for col in cols if len(col) > 0] plt.figure(figsize=(16, 6), dpi=150) plt.xlim(0, dw) for p in [0, 10, 25, 50, 75, 90, 100]: plt.plot([np.percentile(col, p) for col in cols if len(col) > 0], 'k', linewidth=0.5, label=f'{p}%') plt.plot(mvalues.mean(axis=0), 'red', linewidth=2, label='mean') plt.legend() plt.show() Plot for first picture: Plot for second picture:
73,105,084
73,105,159
What does the system put in buffer when you enter RETURN in keyboard
It is well known that say if we use a loop of cin.get(char_array, 10) to read keyboard input. It will leave a 'delimiter'(corresponds to the 'ENTER' key) in the queue so the next iteration of cin.get(char_array, 10) will read the 'delimiter' and suddenly closed. We have to do this cin.get(char_array, 10) cin.get() use an additional cin.get() to absorb the 'delimiter' so that we can input several lines in prompt in a row. I really wonder here is, what exactly is the delimiter in the queue? Is it just '\0' which marks the end of a string? Say if I type "Hello" in prompt and push ENTER button, will the queue be like {'H','e','l','l','o','w','\0'}? If the delimiter(corresponds to the ending "ENTER" key) is not '\0', will there be a '\0' automatically added to the end of the queue? say {'H','e','l','l','o','w','whatever_delimiter','\0'} This question matters cause if we use a char* to store the input, we may consider extra places for those special marks. The actual chars you can store is fewer than you the seats you applied.
The 'queue' associated with std::cin (it's normally known as a buffer) is the characters you type. This is true however you read from std::cin. get(array, count, delim) reads until 1) end of file is reached, 2) count - 1 characters have been read, or 3) the next character in the queue is delim. If not supplied delim defaults to '\n'. So in your case the delim is '\n' and the read will continue until '\n' is the next character in the queue (assuming the read stops for reason 3 above). A '\0' is added to array (assuming there is room) by the get function. It's never the case that '\0' is added to the queue.
73,105,115
73,133,436
How can Visual Studio C++ debugger be showing values of local variables that are at odds with another frame?
I'm building a game in UE5 with C++. If you have access to the Unreal Engine source code (get it here), I'm hitting an assertion on this line: https://github.com/EpicGames/UnrealEngine/blob/d9d435c9c280b99a6c679b517adedd3f4b02cfd7/Engine/Plugins/Runtime/StateTree/Source/StateTreeModule/Private/StateTreeExecutionContext.cpp#L682 When I look at the Visual Studio debugger it shows the assertion error: Array index out of bounds: 65533 from an array of size 5 But when I look at the Locals window that array index (stored in CurrentStatus.State.Index) has a value of2, not 65533. How can this be? The relevant source code is: for (FStateTreeHandle Handle = CurrentStatus.State; Handle.IsValid(); Handle = StateTree->States[Handle.Index].Parent) { const FBakedStateTreeState& State = StateTree->States[Handle.Index]; ... } The assertion is hit the first time through the for loop when calling StateTree->States[Handle.Index], so Handle.Index is getting the value CurrentStatus.State.Index (which is 2). If I click into the frame where it's validating the array index, the Locals window does show Index is 65533. See a screenshot of this issue here: Visual Studio debugger Per this screenshot the variable Handle was optimized away, but it seems it was optimized to have the wrong value. I can't imagine this is a bug in the C++ compiler, so what else could it be?
Turns out the comments on the question gave me the right clue here: The bottom line is that you cannot simply debug optimized code, and expect the debugger to adjust itself to the optimizations done by the compiler. When I debugged using a non-optimized build of UE5, I quickly saw the issue, and the CurrentStatus.State.Index is in fact 65533. In case others run into this, it's not enough to use the "DebugGame Editor" config in the Visual Studio project for your game. That config only compiles your game's code without optimizations, the engine is still run using optimized code. To run the engine without optimized code, you need to build it from source and use the "Debug Editor" Visual Studio config to disable optimizations. Then you can run your game by changing the path of the UE exe it uses in the Visual Studio project of your game from the project Property Pages under the Debugging section.
73,105,304
73,105,475
How to find out if a std::vector in a string in cpp?
I have a string like ...hello...world..., and I want to check if it is in some strings,so I split it by ... and save it in a <vector> string,the problem is how to check both of item in input_str sequentially? #include <iostream> #include <vector> using namespace std; int main() { string input_str1 = "Good morning, hello, a beautiful world";//true string input_str2 = "what a wonderful world, hello!"; //false, but I only can return true //item = "...hello...world..." vector<string> item; item.push_back("hello"); item.push_back("world"); bool status = false; for (auto sub_item : item) { cout << sub_item << ' '; if (input_str2.find(sub_item) != string::npos) //change str1 to str2 status = true; else { status = false; break; } } cout << status; } Checking input_str1 works fine, but for input_str2 the output should be 0 because the two words appear not in the right order. My code prints 1 for both.
Initialize bool status = true; and remove status = true;. You start with the assumption that the string contains all words. Then, you iterate over the list of words and check each word. If a word doesn't exist, set status = false;. Store the position of the last result and start the next search at that position. #include <iostream> #include <vector> int main() { std::string input_str1 = "Good morning, hello, a beautiful world";//true std::string input_str2 = "what a wonderful world, hello!"; //false, but I only can return true //item = "...hello...world..." std::vector<std::string> item; item.push_back("hello"); item.push_back("world"); bool status = true; std::string::size_type pos = 0; for (auto sub_item : item) { std::cout << sub_item << ' '; pos = input_str2.find(sub_item, pos); if (pos == std::string::npos) { status = false; break; } } std::cout << status; } Output hello world 0
73,105,807
73,106,641
MFC Multithread Raw Data Viewer Program Design
The program I'm working on has the following features: Display the incoming data (thru an ethernet UDP socket) Manipulate and calculate some data in the header and display Save a # of frames upon user input The program has the following structure: a Main UI thread running (provided by MFC) a thread which takes the dialog itself, this, as a parameter and is in charge of receiving the data through the UDP socket a thread which also takes the dialog pointer, this and is in charge of displaying the data The data receiving thread is using a buffer to store data and the buffer is a member of the dialog class. What makes this possible is, in the display thread, I can access the data stored in the buffer with the use of the dialog pointer and display it; such as StretchBlt(....., pdlg->vbuf[0].data, ....);. It really isn't much complicated. The program runs smooth until there is a user input (windows messages, or more). It crashes at: Most frequent crash point CEXAMPLEAPP::InitInstance() { ... CEXAMPLEDlg* pdlg = new CEXAMPLEDlg; m_pMainWnd = pdlg; INT_PTR nResponse = pdlg->DoModal(); <-------------------------------------------- if( pdlg!=NULL ) { delete pdlg; m_pMainWnd = NULL; } ... } nResponse turns out to have a huuuuge negative value (something like 19 decimal degits) which I don't think is a normal behaviour. It also crashes at a couple different locations. Most of them are reading violations or dll errors which are hard to interpret and track the cause. I have done some research, the possible causes of the crashes are: i) The dynamically allocated dialog object is a local. Therefore the allocated memory isn't enough to process the infinitely incoming data. That's why it's causing reading violations at random locations. ii) Another possible cause is that most of the variables, including the frame buffers, are member variables - the program is using two separate worker threads and they all are taking the dialog pointer as a parameter. Even though the reading and the writing to the buffer routine are done within CCriticalSection lock(), and unlock() inside the thread functions (global), the variables' ownership could be the possible cause. This is where I'm at right now. Any ideas to fix the crashes? Any thoughts on using the variables as member variables of the dialog class? The threads are communicating through SetEvents() and WaitforSingleObject() btw.
When you display the data (StretchBlt(....., pdlg->vbuf[0].data, ....);) in the display thread and this is accessing the display DC, you have to make sure you are doing it in sync with the main thread, for example, by using atomic locks. Or as an alternately better solution, do the display in main thread and remove the display thread altogether.
73,106,189
73,106,546
Ambiguity when calling overloaded function with vector as param
I am writing a class in which I am overloading operator[] and I want one function to have vector as input and the second one to have vector of vectors as input, but when I call it like obj[{ 0 }] then I got ambigious call error. The functions are declared like const Tensor operator[](const std::vector<std::vector<uint32_t>>& ranges) const; const float operator[](const std::vector<uint32_t>& index) const; Is there any way to handle that ambiguity?
{0} has no type. and it is valid to construct both std::vector<uint32_t> and std::vector<std::vector<uint32_t>> (without overload resolution preference). You might specify the type explicitly at call site: obj[std::vector<uint32_t>{0}]; obj[std::vector<std::vector<uint32_t>>{0}]; or add extra overload with higher priority: Tensor operator[](const std::vector<std::vector<uint32_t>>& ranges) const; float operator[](const std::vector<uint32_t>& index) const; float operator[](const std::initializer_list<uint32_t>& ini) const { return operator[](std::vector(ini)); } Demo
73,106,332
73,108,189
Find the remainder after dividing the sum of two integers by the third
I'm trying to find a solution to a task. My code passed only 3 autotests. I checked that the solution satisfies the max/min cases. Probably there are situations when my code is not valid. Description of the task: Find the remainder after dividing the sum of two integers by the third. Input: The first line of input contains two integers A and B (-10^18 ≤ A, B ≤ 10^18). The second line contains an integer C (2 ≤ C 10^9). Output: Print the remainder of dividing A + B by C. My code: #include <iostream> // int64_t #include <cstdint> #include <stdint.h> // #include <math.h> // 3 tests passed int main() { int64_t a, b, c; std::cin >> a >> b >> c; // a = pow(-10, 18); // b = pow(-10, 18); // // c = pow(10, 9); // c = 3; // c = pow(10, 18) - 20; // c = 1000000000000000000 + 1; // c = 1000000000000000000 + 2; // std::cout << a << std::endl; // std::cout << b << std::endl; // std::cout << c << std::endl; std::cout << (a + b) % c << std::endl; return 0; }
Please note that in C++ reminder for negative values: was implementation defined until C++11 integer division is rounded towards zero since C++11 which makes reminder negative sometimes. Now most probably in your task modulo result should be always in range <0, C) (or written differently <0, C - 1>). So to handle cases where A + B is negative, you have to take this into account that reminder may be negative. So your code can look like this: nt main() { int64_t a, b, c; std::cin >> a >> b >> c; std::cout << (a + b) % c + ((a + b) % c < 0) * c << '\n'; return 0; } Which basically adds c to result if result is negative and makes result inside required range. (assuming c is positive).
73,106,847
73,106,967
Terminate called without an active exception : LeetCode Question 74
I'm writing a simple program to search for an element in a 2D matrix. It's not giving me an active/named exception, but it just throws me a Runtime error. Any help with as to why this is happening? class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { for (int i=0 ;i< matrix.size(); ++i){ int m = matrix[i].size() -1 ; int n = matrix.size()-1; if (matrix[n][m] < target){ return false; } else if (matrix[i][m] < target){ i++; } else { for (int j=0;j <= m; j++ ){ if (matrix[i][j] == target){ return true; } else if (matrix[i][j] != target) { continue; } } if (matrix[i][m] != target ){ return false; } } }throw; } };
}throw; A throw without following expression can be used inside an exception handler to re-throw the currently handled exception. However, at this point your program does not have an active exception. In this case, throw calls std::terminate(). This seems to be an edit artifact.
73,107,077
73,107,249
Function template overload with constraints
I have the following code: // converters.h #pragma once #include <iostream> #include <type_traits> template <typename TTo, typename TFrom> static TTo convert(const TFrom& from) { TTo t = static_cast<TTo>(from); std::cout << "From type: " << typeid(TFrom).name() << "\nTo type: " << typeid(TTo).name(); return t; } template<typename TTo, typename TFrom> static int convert(std::enable_if_t<std::is_enum_v<TFrom>, TFrom> const& from) { std::cout << "[X] From type: " << typeid(TFrom).name() << "\nTo type: " << typeid(TTo).name(); return 0; } // Main.cpp #include "converters.h" enum class Season { Spring, Summer, Autumn, Winter }; int main() { convert<int>(Season::Spring); return 0; } I want to add some constraints to TFrom or TTo or both as function template specialization, but somehow it's not working. The more stricter version of the function template specialization is not getting called. In the above example, I expect the second one is getting called, however, it is still calling the primary one. How can I add constraints to function template specialization? What if TTo or TFrom is STL types, like std::unordered_map<TKey, TVal>? What I want to do is to convert from any type to the other type with this convert function call. If the primary template doesn't meet the need, then just add a new specialization. Anyone can give some guidance on how to achieve this purpose? Thanks. Any input is appreciated. Note: I know some c++20 concept can add constraints, but let's assume it's c++17 due to some reason.
In this function declaration: template<typename TTo, typename TFrom> static int convert(std::enable_if_t<std::is_enum_v<TFrom>, TFrom> const& from); type TFrom appears in a non-deduced context. So, when you call: convert<int>(Season::Spring); the compiler can only call (due to SFINAE) template <typename TTo, typename TFrom> static TTo convert(const TFrom& from); You may get the behavior you expect by SFINAE-ing on the return type, i.e.: template <typename TTo, typename TFrom> static std::enable_if_t<!std::is_enum_v<TFrom>, TTo> convert(TFrom const& from) { TTo t = static_cast<TTo>(from); std::cout << "From type: " << typeid(TFrom).name() << "\nTo type: " << typeid(TTo).name(); return t; } template <typename TTo, typename TFrom> static std::enable_if_t<std::is_enum_v<TFrom>, int> convert(TFrom const& from) { std::cout << "[X] From type: " << typeid(TFrom).name() << "\nTo type: " << typeid(TTo).name(); return 0; } Notes: You need to constrain the return type on both the function templates, otherwise convert<int>(Season::Spring) would result in an ambiguous overload call; Function templates cannot be partially specialized (even though you're not partially specializing it, anyway); As noted in the comments, there's no need for typename TTo in the second version of convert, if you always return int.
73,107,532
73,107,852
Program crashes when using custom compartor for std::set
I tried to use custom comparator in a std::set. When I insert cuisine "japaneses" in a variable bucketCuisines, I get error DEADLYSIGNAL. But, If i eliminate the custom comparator cmp there is no problem. But of course my results are incorrect. Input: ["FoodRatings","highestRated","highestRated","changeRating","highestRated","changeRating","highestRated"] [[["kimchi","miso","sushi","moussaka","ramen","bulgogi"],["korean","japanese","japanese","greek","japanese","korean"],[9,12,8,15,14,7]],["korean"],["japanese"],["sushi",16],["japanese"],["ramen",16],["japanese"]] Result: [null, "kimchi", "ramen", null, "sushi", null, "ramen"] class FoodRatings { public: static bool cmp(pair<int, string> a, pair<int, string> b){ if(a.first == b.first) return a.second < b.second; return a.first > b.first; } unordered_map<string, int> bucketFoods; unordered_map<string, string> bucketFoodNCuisine; map<string, set<pair<int, string>, decltype(cmp)*>> bucketCuisines; FoodRatings(vector<string>& foods, vector<string>& cuisines, vector<int>& ratings) { int n = foods.size(); for(int i=0; i<n; i++){ bucketFoods.insert(make_pair(foods[i],ratings[i])); cout << "1 ok\n"; bucketFoodNCuisine.insert(make_pair(foods[i], cuisines[i])); cout << "2 ok\n"; bucketCuisines[cuisines[i]].insert(make_pair(ratings[i], foods[i])); cout << "3 ok\n"; } } void changeRating(string food, int newRating) { int oldRating = bucketFoods[food]; bucketFoods[food] = newRating; string temp = bucketFoodNCuisine[food]; bucketCuisines[temp].erase(bucketCuisines[temp].find(make_pair(oldRating, food))); bucketCuisines[temp].insert(make_pair(oldRating, food)); } string highestRated(string cuisine) { return bucketCuisines[cuisine].begin()->second; } };
Your data type set<pair<int, string>, decltype(cmp)*> is an odd way to specify the comparator as a function pointer. But that's what it does, and the issue is likely because you never provide a valid comparator when constructing these sets. When you add an entry to bucketCuisines, you're currently relying on the default constructor for this set. But that will initialize the comparator function pointer to nullptr. When you go to add stuff to the set, the null comparator is invoked and your program crashes. The simplest way around this is to make the comparator a functor instead: struct cmp { bool operator()(const pair<int, string>& a, const pair<int, string>& b) const { if(a.first == b.first) return a.second < b.second; return a.first > b.first; } }; map<string, set<pair<int, string>, cmp>> bucketCuisines;
73,108,025
73,108,171
Why does the freed memory is less than allocated memory when overloading new and delete operators?
I created a class and overloaded new and delete operators to print the size of memory allocated/freed. In the example below, it allocated 28 bytes but frees 4 bytes. Why? #include <iostream> #include <string> using namespace std; class Person { private: string name; int age; public: Person() { cout << "Constructor is called.\n"; } Person(string name, int age) { this->name = name; this->age = age; } void* operator new(size_t size) { void* p = malloc(size); cout << "Allocate " << size << " bytes.\n"; return p; } void operator delete(void* p) { free(p); cout << "Free " << sizeof(p) << " bytes.\n"; } }; int main() { Person* p = new Person("John", 19); delete p; } output: Allocate 28 bytes. Free 4 bytes.
sizeof(p) is the size of void*, the size of a pointer to void. It is not the size of the block of memory to which this pointer is pointing, that is sizeof(Person). A void* alone carries no information on the size of the pointee. Though, in the background free "knows" how big is the memory block associated with p because you specified the size when you used malloc. If you would implement your own memory managment rather than falling back to free/malloc (eg you could use a memory pool that uses some big block of preallocated memory) then you would need to implement such mapping from pointer to size of the memory block as well.
73,109,010
73,109,366
How to access ui element from another dialog
I have a this code for get avaiable serial ports on Main Window. QString parsedPortName = QSerialPortInfo::availablePorts().at(ui -> comboBoxDevices -> currentIndex()).portName(); I need access this avaiable ports from another Page. Hiw can I do that? Here, on my Second Window I need replace avaiable comports with (QString("COM3") if (serialStartStop.begin(QString("COM3"), 9600, 8, 0, 1, 0, false)) { serialStartStop.send("B" + ui->baslatmaedit->text().toLatin1() + "D"+ ui->durdurmaedit->text().toLatin1()); }
The usual way would be to have something like this in the first dialog: QString parsedPortName = QSerialPortInfo::availablePorts().at(ui -> comboBoxDevices -> currentIndex()).portName(); emit portNameChanged(parsedPortName); // add this signal to the class And then in the second window, you would have a slot, which receives the port name, and stores it in a member variable. Then in the code where you create these two windows or dialogs, you add the connect call for the signal and the slot. Since this port is something, which you might want to save between different times the application is run, you could also use QSettings to store the combo box selection, and restore it to the combo box when application starts, and change it when user changes it in the combo box. In this case, you'd probably want to move the QSerialPortInfo::availablePorts() call to the second window, done just before the port name is actually used. In my experience, the best way to use QSettings is to first set it up in main(): QCoreApplication::setOrganizationName("MyImaginaryOrganization"); QCoreApplication::setApplicationName("MyComPortApp"); After that, it will store the settings in operating system specific, generally good, way. And then you can just use it like this anywhere in your application: QSettings().setValue("serial/portname", parsedPortName); and elsewhere auto port = QSettings().value("serial/portname").toString(); Instead of using QSettings, you might create your own singleton class like that, but really, QSettings exists and is quite nice for the purpose, so just use it unless you have some compelling reason to write your own. You can of course also combine these two things: use QSettings with the combo box only, and still emit a signal when it is changed.
73,109,477
73,109,578
Class member names as non-type template parameter
I have a class which is generated from a tool with member variable names that vary. I would like to use a single templated class to access these members. I can do this in the following way by using a non-type member pointer: template<typename MODULE, int MODULE::*a> class Foo { public: Foo() { MODULE mod; std::cout << mod.*a; } }; struct Bar { int random_name01234{20}; }; int main(int argc, char** argv, char** env) { Foo<Bar, &Bar::random_name01234> foobar; } However, the generated class (Bar in this example) uses references to members I do not have access to. I cannot pass a reference as a non-type template parameter as described here - Reference as a non-type template argument: template<typename MODULE, int& MODULE::*a> class Foo { public: Foo() { MODULE mod; std::cout << mod.*a; } }; class Bar { private: int random_name01234{20}; public: int& random_name01234_ref{random_name01234}; }; int main(int argc, char** argv, char** env) { Foo<Bar, &Bar::random_name01234_ref> foobar; } error: cannot create pointer to reference member ‘Bar::random_name01234_ref’ Is there another way I can approach this to pass the random member names to a templated function?
You cannot have a pointer to reference member (see eg How to obtain pointer to reference member? and Reference as a non-type template argument), but you can have a pointer to member function that returns the value by reference: #include <iostream> template<typename MODULE, int& (MODULE::*a)()> class Foo { public: Foo() { MODULE mod; std::cout << (mod.*a)(); } }; class Bar { private: int random_name01234{20}; public: int& random_name01234_ref{random_name01234}; int& get() { return random_name01234_ref;} }; int main(int argc, char** argv, char** env) { Foo<Bar, &Bar::get> foobar; } If you cannot modify Bar then you just have to use a different callable that returns the reference. Anyhow I consider int (MODULE::*a)() as too non-generic. I'd rather let Foo accepts any callable, for example a lambda expression: #include <iostream> template<typename MODULE, typename F> class Foo { public: Foo() { MODULE mod; std::cout << F{}(mod); } }; class Bar { private: int random_name01234{20}; public: int& random_name01234_ref{random_name01234}; }; int main(int argc, char** argv, char** env) { Foo<Bar,decltype([](Bar& b)->int&{ return b.random_name01234_ref;})> foobar; } Lambda expression in unevaluated context is only available since C++20. Before it works as well, just a little more verbose.
73,109,985
73,110,268
Elegant way to access objects created in qApplication main function
I want to create a window application with Qt framework and C++, in which an object is created to operate hardware, and should be accessible to MainWindow and all its members and methods. I do not have very much experience of doing things like this. int main(int argc, char *argv[]) { QApplication qApp(argc, argv); CoolHardware *CoolHardware500 = new CoolHardware; // Object that connects to hardware. CoolHardware500.Connect(); // Show main window here. MainWindow qApp_Win(CoolHardware500); // This is the only elegant way I could think. qApp_Win.show(); return qApp.exec(); // Deconstructor. CoolHardware500>~CoolHardware(); } In the methods of MainWindow, is not accessible. How to solve this? void MainWindow::CoolHardwareDoSomething() { CoolHardware500->DoSomehing(); // Here CoolHardware500 is shown as not defined. } Questions: Is it an elegant way to create an hardware-operating object in the main() function? How to make it accessible to the members/methods of the MainWindow? Is it better to create objects in the constructor of the MainWindow and deconstruct objects in the MainWindow deconstructor? In this way, accessing object is easy. If this two ways are both not elegant ways of doing things, what is the elegant way of doing that? Thank you very much.
MainWindow is subclassing QMainWindow, but it's a regular C++ class, so just store either an instance directly, or a pointer, as a member variable on it. In MainWindow.h (or .hpp): class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; // Either this: CoolHardware500* m_coolHardwarePtr; // Or that: CoolHardware500 m_coolHardware; }; In the constuctor MainWindow::MainWindow you can pass arguments to the CoolHardware500 ctor as needed, or use a new if you use a pointer. If using a pointer, you also want to have the destructor MainWindow::~MainWindow do a delete m_coolHardwarePtr;. You could also use a smart pointer (like std::unique_ptr) to avoid to remember to do that delete yourself. Mainwindow.cpp, assuming you have a Ctor CoolHardware500::CoolHardware500(int): MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow), m_coolHardware(1), m_coolHardwarePtr(new CoolHardware500(1)) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; delete m_coolHardwarePtr; }
73,110,191
73,110,334
Unable to initialize a template variable inside a class, why?
I don't understand why if I initialize this template variable globally, like this: template <class T> struct null_string { static const std::string value; }; template<class T> const std::string null_string<T>::value = ""; template<class T> std::string const null_str = null_string<const T&>::value; it works, but if I try to initialize it inside a class, like this: class foo { template <class T> struct null_string { static const std::string value; }; template<class T> const std::string null_string<T>::value = ""; template<class T> std::string const null_str = null_string<const T&>::value; }; it gave me an error: prove.cpp:8:65: error: invalid use of qualified-name ‘foo::null_string<T>::value’ 8 | template<class T> const std::string null_string<T>::value = ""; | ^~ prove.cpp:11:78: error: data member ‘null_str’ cannot be a member template 11 | template<class T> std::string const null_str = null_string<const T&>::value; | Do you know why?
Add missing static. Then, either move variable definitions to namespace scope: class foo { template <class T> struct null_string { static const std::string value; }; template <class T> static std::string const null_str; }; template <class T> const std::string foo::null_string<T>::value = ""; template <class T> std::string const foo::null_str = foo::null_string<const T&>::value; Or make them inline: class foo { template <class T> struct null_string { inline static const std::string value = ""; }; template <class T> inline static const std::string null_str = foo::null_string<const T&>::value; };
73,110,731
73,110,829
Importing x86_64 DLL in project with x86 environment through P/Invoke
My current target framework is .NET Framework v4.0. I'm having issues importing the DLL as I get the "BadImageFormatException" similar to this post BadImageFormatException when loading 32 bit DLL, target is x86 From there I realised that the DLL (retrieved from NuGet) can only be built in x64, but my solution can only be x86 as that is what the team has decided on. So I can't change the configuration to x64. I'm currently using P/Invoke to import it (DllImport). My machine is x64. For context, this DLL is built with managed native c++ code and I am trying to convert it to c#. I cannot touch the dll as it is not my library, but my project is in c#. Since I am not allowed to change my project settings, and the DLL can only be built in and run in x64, is there any other way to solve this issue?
You can not load a 64-bit dll in a 32-bit process. Your options are: Update your application to x64 mode. This typically requires all native components to be changed to x64 versions. You said you team decided on x86, but decisions can be re-evaluated if you have good enough reasons to. Find a way to get a x86 version of your library. This might involve creating your own build, so it might be expensive. Run your library in a separate process, and use your favorite RPC/IPC method to communicate between the processes. This will typically make deploying and debugging your application at least a bit more difficult, depending on how frequently the library is used.
73,112,048
73,112,060
Difference in function argument between int pointer and int array
What is the difference between taking as a function argument an int pointer or an int array in C++? void arrayFunction1(int * x) { for(int i = 0; i < 10; i++) { cout << x[i] << endl; } } void arrayFunction2(int x[]) { for(int i = 0; i < 10; i++) { cout << x[i] << endl; } } int main() { int dstdata[10]; arrayFunction1(dstdata); arrayFunction2(dstdata); return 0; } Both results look the same to me.
There are completely identical. In a function parameter int x[] is just another way of writing int* x. Even int x[10] is the same (the 10 is completely ignored). Now why Kernighan and Ritchie (the inventors of C) thought this piece of deception was a good idea is another question. I guess they weren't thinking of all the people who have to learn the syntax.
73,112,288
73,131,728
Can Qt Remote Objects be used to share an entire mainwindow UI?
I'm currently looking into Qt RO as a possible solution for my current need to remotely access a UI without using Qt WebGL. I am having trouble finding any good example uses of Qt RO outside of the starter ones in the qt docs. Will Qt RO fit my needs and does anyone know of a good example?
Custom types work just fine with Qt Remote Objects. Just like with any other meta object compiler issue in Nuke, you just need to make sure that the type is known to the meta object compiler. So, for example, you will need to register it. PROP(SomeOtherType myCustomType) // Custom types work. Needs #include for the // appropriate header for your type, make // sure your type is known to the metabject // system, and make sure it supports Queued // Connections (see Q_DECLARE_METATYPE and // qRegisterMetaType) https://doc.qt.io/qt-6/qtremoteobjects-repc.html#prop You can also find more information about how to handle custom types in Qt in general here. You would register your type like this: Q_DECLARE_METATYPE(Message); https://doc.qt.io/qt-6/custom-types.html
73,113,173
73,113,358
How to implement cast for "smart pointer" non-const to const
I am attempting to understand the internals of std::shared_ptr by writing my own (VERY BASIC) implementation. What I have so far is the following (with most of the operators and other code removed). template <typename T> struct ControlBlock { unsigned int refCount; T* ptr; }; template <typename T> class MyPointer { //... private: ControlBlock<T>* _cb; }; Everything has been working fine so far except when I try to do the following: MyPointer<Foo> ptr1; MyPointer<const Foo> ptr2 = ptr1; In this case, the non-const pointer cannot be converted to the const pointer because they are two completely different types as far as the template expansion is concerned. How do I write the pointer in such a way that it allows this (implicit) conversion? EDIT I know know from the comments that the pointer should be better implemented as: struct ControlBlock { unsigned int refCount; }; template <typename T> class MyPointer { private: T* _ptr; ControlBlock* _ctrl; }; Ultimately, I would like to use this with my own memory pool which will allocate the following: template <typename T> struct ControlBlockWrapper { ControlBlock ctrl; T value; }; If my control block contains a pointer back to my pool, I am very confused how I can get from from T* and ControlBlock* (stored by the pointer) to a pointer to the real ControlBlockWrapper that will need to be deleted from the pool. For example, since my pool is creating ControlBlockWrapper's, it's delete method would look something like: template <typename T> class Pool { //... void destory(ControlBlockWrapper<T>* ptr); }; Pointer arithmetic seems like a poor way to accomplish this, but I'm not sure how else to do it.
How to implement cast for "smart pointer" non-const to const Implement exactly that - a conversion operator from non-const to const. With help of how can I use std::enable_if in a conversion operator? to do some SFINAE: #include <iostream> #include <type_traits> template <typename T> struct ControlBlock { unsigned int refCount; T* ptr; }; template <typename T> struct MyPointer { template< typename T2 = T, typename = typename std::enable_if_t<std::is_same_v<T2, std::remove_const_t<T2>>> > operator MyPointer<const T2>() { // do some magic conversion stuff here MyPointer<const T2> ret{nullptr}; return ret; } ControlBlock<T>* _cb; }; class Foo; int main() { MyPointer<Foo> ptr1; MyPointer<const Foo> ptr2 = ptr1; }
73,113,250
73,113,309
Why returning string is not printing in C++
I am having an issue with my C++ code. I am learning C++. I have written a C++ code for deleting a character from a string. My code is running without an error but not getting a output. My Code: #include <iostream> #include <string> using namespace std; string deletion(string s, int position) { string newS; int i = 0, j = 0, sLen = s.length(); while(sLen != 0) { if(i != position) { newS[j] = s[i]; j++; } i++; sLen--; } return newS; } int main() { cout << deletion("abcd", 2) << endl; return 0; } Why I am not getting any output? How to solve this problem?
This string has zero length string newS; This code attempts to write a character to a zero length string newS[j] = s[i]; That is an out of bounds error and therefore your code has undefined behaviour. Here's your code rewritten so that it adds characters to the string. string deletion(string s, int position) { string newS; int i = 0, sLen = s.length(); while(sLen != 0) { if(i != position) { newS.push_back(s[i]); } i++; sLen--; } return newS; } I haven't checked the rest of the logic, but this code is clearly the code you were trying to write. You're not the first beginner to think that strings grow automatically when you write characters to them, but this is not true.
73,113,402
73,114,714
I need to read txt file and have each line run through the code in c++. I tried while before if statement and got caught in a loop
not very good at coding yet, and I am doing a c++ program that needs to read txt file and take line-by-line string input and iterate it through the program. each line has 18 numbers. It reads the lines but only cycles the last line. I need it to run all lines through the equation, so I can verify the checksum of each using the order set and weight with modulo 11. That part is fine, and it is working. This is the main part of the program. did not include all 200+ lines as they are just switch if else and some conversions. if needed, I can upload it all. #include <iostream> #include <string> #include <vector> #include <sstream> #include <fstream> using namespace std; int main() { stringstream cs; stringstream ss; stringstream rr; stringstream mm; string input; //This is for manual inputs //cout << "Enter 18 digit number: "; //cin >> input; std::ifstream File ("idnumbers.txt"); //Checking the file opening condition if (File.is_open()) { while (std::getline (File,input)) { cout << input << '\n'; } File.close(); } if (input.length() != 18) { cout << "Length of ID is incorrect." << endl; return 1; } int orderedSet[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; string index = "10X98765432"; int sum = 0; for (int i = 0; i < 17; i++) { sum += (input[i] - '0') * orderedSet[i]; }
First of all you have to understand what is the use of the instruction using namespace std; Because you don't need to put std:: before the getline() for example. It's normal that your code treats only the last line of your text file because it's this line that you store last before closing the file. If you want to continue with your blocks as they are, you will have to use a container (a vector for example to store all the lines). But that would be complicating your life for nothing. To make it simpler, with your same code, you can just do this: ifstream File ("idnumbers.txt"); //Checking the file opening condition if (File) { while (getline (File,input)) //We read all lines { cout << input << endl; if (input.length() != 18) { cout << "Length of ID is incorrect." << endl; return 1; } int orderedSet[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; string index = "10X98765432"; int sum = 0; for (int i = 0; i < 17; i++) { sum += (input[i] - '0') * orderedSet[i]; } } File.close(); } There are variables in your code that are not used. For example, sum is not used because you don't use it. NB: I have not tested this code and it is yours. I just moved some blocks following the logic. Soory for my poor english.
73,113,594
73,114,139
Built-in way to pass JS objects to C++ using emscripten
Is there a simple built-in way to pass JS objects to C++? I tried doing it the obvious way: echo.cpp: #include <iostream> #include <emscripten.h> #include <emscripten/val.h> using emscripten::val; #ifdef __cplusplus extern "C" { #endif EMSCRIPTEN_KEEPALIVE void echo(val x){ val::global("console").call<void>("log", x); } int main(int argc, char **argv){ return 0; } #ifdef __cplusplus } #endif script.mjs: import initEM from "./echo.mjs"; var mod = await initEM(); export function echo(x){ mod.ccall("echo", "void", ["object"], [x]); } echo({attr: 9}); Compiled using: emcc ./echo.cpp -o ./echo.mjs \ -sEXPORTED_FUNCTIONS=_main,_echo \ -sEXPORTED_RUNTIME_METHODS=ccall,cwrap,registeredTypes \ -lembind --bind But I got an error: Uncaught TypeError: Cannot read properties of undefined (reading 'refcount') at __emval_incref (echo.mjs:2622:29) at echo.wasm:0x1957 at echo.wasm:0x1842 at echo.wasm:0x121c at echo.wasm:0x110f at echo.wasm:0x104a at echo.mjs:1639:22 at Object.ccall (echo.mjs:845:18) at echo (script.mjs:6:7) at script.mjs:9:1 After some trial and error, I got it to work: echo.cpp: #include <iostream> #include <emscripten.h> #include <emscripten/val.h> using emscripten::val; using emscripten::internal::EM_VAL; #ifdef __cplusplus extern "C" { #endif EMSCRIPTEN_KEEPALIVE void echo(EM_VAL x_ptr){ // converts it to object from the pointer val x = val::take_ownership(x_ptr); val::global("console").call<void>("log", x); } int main(int argc, char **argv){ return 0; } #ifdef __cplusplus } #endif script.mjs: import initEM from "./echo.mjs"; var mod = await initEM(); let objToC = null; for(let tp of Object.values(mod.registeredTypes)){ if(tp.name=="emscripten::val"){ // turns it into a pointer (I think) objToC = (v) => tp.toWireType(null, v); break; } } if(objToC==null){ throw new ReferenceError("val.toWireType not found"); } export function echo(x){ mod.ccall("echo", "void", ["number"], [objToC(x)]); } echo({attr: 9}); (Compiled using same thing as the other one) Questions: Why isn't this already in the ccall/cwrap functions? Why doesn't emscripten expose the val.toWireType as an attribute of the module object (i.e. why do I have to loop through all types to find it), or is there something I've missed?
Via the docs : EMSCRIPTEN_BINDINGS(my_module) { function("lerp", &lerp); } my_module is just a (globally) unique name you have to add, it doesn't have any other purpose. void echo(EM_VAL x_ptr){ // converts it to object from the pointer val x = val::take_ownership(x_ptr); val::global("console").call<void>("log", x); } EMSCRIPTEN_BINDINGS(my_bindings) { function("echo", echo); } now you can invoke echo from JS without using ccall: Module.echo({addr: 9}); note that this doesn't work well from a webworker; the registration of the echo method in Module is done as part of WASM initialization, and only in the initializing thread. While EMSCRITEN_BINDINGS looks magical, it basically just makes a static global function and calls it at static construction time. It is function("echo", echo); that does all of the work; it determines the arguments of echo, and builds a JS wrapper that converts arguments and calls the C++ function echo, using the name "echo".
73,113,840
73,116,691
C++ - Automatically insert a pair-like object into a map?
Lets say we have some pair like class: class PairLike{ public: string key; int val; PairLike(string Key, int Val) : key(Key), val(Val){}; //...other members }; A few objects to go along with it: PairLike p1("a",1); PairLike p2("b",2); PairLike p3("c",3); PairLike p4("d",4); Is there a way of automatically working with this object? For example, something similar to: std::map<PairLike> container = {p1,p2,p3}; container.insert(p4); Instead of writing something like: std::map<string, int> container = {{p1.key, p1.val}, {p2.key, p2.val}, ... } container.insert({p4.key, p4.val}) I'm aware that using an std::set<PairLike> with a comparator using is_transparentcan achieve the result I'm looking for. However, I am curious if there is any way to approach this problem with a map.
You could provide a conversion operator for converting to std::pair: class PairLike{ public: // ... operator std::pair<const std::string, int>() { return {key, val}; } }; And use it like: std::map<string, int> container{p1,p2,p3}; container.insert(p4);
73,114,876
73,114,999
Why do I get a weird error about an uninstantiated template being undefined?
When I compile this code with MSVC: #include <type_traits> template<class> struct S { }; template<class T> using Foo = std::integral_constant<unsigned, sizeof(S<std::underlying_type_t<T>>)>; int main() { } I get: error C2027: use of undefined type 'S<_Underlying_type<_Ty,std::is_enum_v<_Ty>>::type>' note: see declaration of 'S<_Underlying_type<_Ty,std::is_enum_v<_Ty>>::type>' Why is this? If it's a bug, is there a known workaround?
I think I figured out a workaround (I think it's a longstanding bug): #include <type_traits> template<class> struct S { }; template<class T> struct Bar : std::integral_constant<unsigned, sizeof(S<std::underlying_type_t<T>>)> { }; template<class T> using Foo = typename Bar<T>::type; int main() { }
73,114,946
73,115,351
c++ TCP client and server not able to communicate on local machine
I have built a simple c++ TCP server and client using winsock. The code all compiles without error however either the server is refusing connections or my client is failing to connect properly. The code is alot to put onto stackoverflow so here is a pastebin for the server and Client. https://pastebin.com/ZQavPxsR - Server Code https://pastebin.com/cLFVp2B1 - Client Code sockaddr_in clientService; clientService.sin_family = AF_INET; InetPton(AF_INET, _T("127.0.0.1"), &clientService.sin_addr.s_addr); clientService.sin_port = htons(port); if (connect(clientSocket, (SOCKADDR*)&clientService, sizeof(clientService)) == SOCKET_ERROR) { std::cout << "Client: connect() = Failed to connect." << std::endl; WSACleanup(); system("pause"); return 0; } else { std::cout << "Client: connect() is OK." << std::endl; std::cout << "Client: Can start sending and reciving data... " << std::endl; } Above is a snippet of the code that is from the client and is responsible for making the connection with the server. acceptSocket = accept(serverSocket, NULL, NULL); if (acceptSocket == INVALID_SOCKET) { std::cout << "Accept Failed: " << WSAGetLastError() << std::endl; WSACleanup(); return -1; } else { std::cout << "Accepted connection " << std::endl; system("pause"); WSACleanup(); } Above is a snippet of the code that is from the server and is responsible for accepting the connection with the client.
Your server is not initializing the service.sin_port field before calling bind(), so the code exhibits undefined behavior. Your listening socket will end up trying to bind to whatever random port value was already present in the memory that the sin_port field occupies. And if that value happens to be 0, then bind() will choose a random port from Windows' available ephemeral ports. In any case, it is very unlikely that your server is ever going to be listening on port 4679, which is the port the client is trying to connect to. On a side note, there are some other problems with your code: In both client and server, your calls to InetPton() should be passing in a pointer to the sockaddr_in::sin_addr field, not the sockaddr_in::sin_addr.s_addr field. It "works" only because s_addr is the sole data member of sin_addr and thus they have the same memory address. But technically, this is undefined behavior since InetPton() wants an IN_ADDR* not a ULONG*. Your server is not exiting if listen() fails, is leaking serverSocket whether accept() succeeds or fails, and is leaking acceptSocket if accept() succeeds. Your client is leaking clientSocket whether connect() succeeds or fails.
73,115,064
73,115,303
How check what boost::datetime correct?
How i can check what input string incorrect and throw exception? Now it string just accepting to constructor and converting to something wrong but exception not throw #include <boost/date_time.hpp> namespace bt = boost::posix_time; using namespace boost; using namespace gregorian; using namespace boost::posix_time; constexpr const char format[] = "%Y-%m-%d %H:%M:%S"; bt::ptime from_string_dtime(const std::string& s) { bt::ptime pt; std::istringstream is(s); is.imbue(std::locale(std::locale::classic(), new bt::time_input_facet(format))); is >> pt; return pt; } class dt_wrap { public: dt_wrap() = default; dt_wrap(const std::string& dtime); ~dt_wrap() = default; private: bt::ptime d_time; }; dt_wrap::dt_wrap(const std::string& dtime) : d_time(from_string_dtime(dtime)) {} int main() { dt_wrap dt("2006-04-25 24:25:25"); dt_wrap dt("incorrect_string"); // need throw exception incorrect format }
Hope it help someone. Need set the streams exception flags. bt::ptime from_string_dtime(const std::string& s) { bt::ptime pt; std::istringstream is(s); is.exceptions(std::ifstream::failbit | std::ifstream::badbit); // Set exception flags is.imbue(std::locale(std::locale::classic(), new bt::time_input_facet(format))); is >> pt; return pt; }
73,115,298
73,115,350
Randomly Generate Even Split of 1s and 0s in Array
I have a simple array, 20 members long, that I read a single value from, one at a time. The array currently looks like this for testing purposes: int PhaseTesting1Array[20] = { 1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0}; What I need to do is randomize each of the members so that each member is randomly a 1 or 0, and there is an equal amount of each (10 ones and 10 zeros) but I'm having a hard time figuring out how to do get an equal number of ones and zeros using rand which seems to be what I should use.
You can use std::shuffle with a predefined vector with 10 ones and 10 zeros. The following code is slightly adapted from cppreference.com. #include <random> #include <algorithm> #include <iterator> #include <iostream> #include <vector> int main() { std::vector<int> v = {1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0}; std::random_device rd; std::mt19937 g(rd()); std::shuffle(v.begin(), v.end(), g); std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; } You could also use std::random_shuffe(I first, I last) without the random number distribution argument which uses rand internally, but this is deprecated and removed with C++17.
73,115,436
73,115,480
How can I use SFINAE to disable a function inside a class based on template type
I have a template class template<typename TLoader, typename TCreator> class ManagerGroup { public: uint32_t loadFromPath(const Path &path) { return mLoader.load(path); } void createFile(uint32_t handle) { return mCreator.create(handle); } private: TLoader mLoader; TCreator mCreator; }; For the loadFromPath and createFile functions, I want to disable them if the provided typename is std::nullptr_t; so, I can do something like this: ManagerGroup<FontLoader, std::nullptr_t> fontManager; // No issues fontManager.loadFromPath("/test"); // Compilation error fontManager.createFile(10); ManagerGroup<std::nullptr_t, MeshCreator> meshManager; // NO issues meshManager.createFile(20); // Throws error meshManager.loadFromFile("/test"); Is this possible with SFINAE? I tried the following but could not get it working (based on example #5 in https://en.cppreference.com/w/cpp/types/enable_if): template<typename = std::enable_if_t<!std::same<TCreator, std::nullptr_t>::value>> void createFile(uint32_t handle) { return mCreator.create(handle); }
In order for SFINAE to work you need to use a parameter that is being deduced. In your case TCreator is already known so you can't use it. You can instead get around the problem by adding your own parameter and defaulting it to TCreator like template<typename T = TCreator, std::enable_if_t<!std::is_same_v<T, std::nullptr_t>, bool> = true> void createFile(uint32_t handle) { return mCreator.create(handle); }
73,115,619
73,115,969
using set_union() with a lambda
I would like to use set_union() and just scan the output without having to store it. Something like this (it doesn't compile using g++12.1.0): #include <vector> #include <algorithm> #include <stdio.h> using namespace std; int main() { vector<int> a = {1,2,3}, b={4,5,6}; ranges::set_union(a, b, [](int i){printf("%d,",i);}); }
You need to supply an "output iterator" for set_union() to pass elements to. It does not accept a lambda (or other callable type). You can use std::ostream_iterator for this, eg: #include <vector> #include <algorithm> #include <iterator> #include <iostream> // ... vector<int> a = {1,2,3}, b={4,5,6}; ranges::set_union(a, b, std::ostream_iterator<int>(std::cout, ","));
73,115,800
73,250,158
Unknown signal exception when debugging on Visual Studio Code
I'm creating a template class for dynamic arrays. The .hpp file is as follows: #include <cstddef> #include <cstring> #include <stdexcept> template <typename T> class array { private: T* m_data; std::size_t m_size; public: array(std::size_t size) : m_size(size) { m_data = new T[size](); } ~array() { delete[] m_data; } std::size_t size() const { return m_size; } T& operator[](std::size_t index) const { if (index >= m_size) { throw std::out_of_range("index is out of range"); } return m_data[index]; } T* begin() {return m_data; } const T* cbegin() {return m_data; } T* end() {return m_data + m_size; } const T* cend() {return m_data + m_size; } }; And the main function: #include "array.hpp" #include <iostream> int main([[maybe_unused]]int argc, [[maybe_unused]]char **argv) { auto t = array<unsigned>(8); t[1] = 45; for (auto item : t) { std::cout << item << std::endl; } } If i run the command g++ *.hpp *.cpp -o main -std=c++20 and just run the binary, everyting is fine. But if I use gdb on Visual Studio Code, it gives an exception called Unknown signal on the line throw std::out_of_range("index is out of range");. What does that mean an why is it throwing this exception? Addendum: For clarification, I'm using Visual Studio Code ver. 1.69.2, C/C++ extension ver. v1.11.4, g++ ver. 12.1.0, gdb ver. 12.1, MSYS2 on Windows 11 ver. 21H2
I eventually found out that there's a compatibility issue between clangd and the Microsoft C/C++ extensions. Uninstalling clangd and reinstalling Microsoft C/C++ solved the issue and other related problems.
73,116,189
73,116,440
Pointers vs vectors for arrays c++
In the case I am creating an 'array' on stack in c++, is it better to initialise an empty vector with a reserved number of elements and then pass this to a function like foo() as a reference as below. Or is it better to set an array arrb of size nelems, then using a pointer p_arrb to the address of the first element increment the pointer and assign some value? #include <iostream> #include <vector> void foo(std::vector<int>& arr){ int nelems = arr.capacity(); for (int i = 0; i < nelems; i++){ arr[i] = i; } } int main() { int nelems; std::cout << "Type a number: "; // Type a number and press enter std::cin >> nelems; std::vector<int> arr; arr.reserve(nelems); // Init std lib vector foo(arr); int arrb[nelems]; int* p_arrb = &(arrb[0]); // pointer to arrb for (int i = 0; i < nelems; i ++){ *(p_arrb++) = i; // populate using pointer } p_arrb -= nelems; // decrement pointer return 0; } It seems people prefer the use of vector as it is standardised and easier to read? Apart from that, is there any performance benefit to using vector instead of a basic pointer in this case where I do not need to change the size of my vector/array at any point in the code?
You can't use the arrb variant because the size of an array must be a compile-time constant in C++, but you are trying to use a runtime size here. If your compiler is compiling this, then it is doing so only because it supports these so-called variable-length arrays as a non-standard extension. Other compilers will not support them or have differing degree of support or behavior. These arrays are optionally-supported in C, but even there they are probably not worth the trouble they cause. There is no way to allocate a runtime-dependent amount of memory on the stack in C++ (except if you misuse recursive function calls to simulate it). So yes, you should use the vector approach. But as discussed in the comments under the question, what you are doing is wrong and causes undefined behavior. You need to either reserve memory and then emplace_back/push_back elements into the vector or you need to resize the vector to the expected size and then you may index it directly. Indexing a vector outside the the range of elements already created in it causes undefined behavior.
73,116,419
73,116,602
How can I pass these references to the same function?
I have a function parse(Stream & in) I'd like to call as both: // asFile() is a static method that returns a Stream object by value parse(Stream::asFile("filename.txt")); and also Stream file = Stream::asFile("filename.txt"); parse(file); file.getPos(); // file retains state set by the parse function But it runs into an issue with lvalues or some such. Is there a way I can write a function so that it will work with both of these parameters?
Is this what you are looking for? #include <iostream> #include <string> // An object to simulate the state of your stream. // Whatever in here must be movable. // Here I am relying on default compiler generated move operators. struct Data { std::string data; }; // You don't provide a definition of stream. // This is the minimum you need. class Stream { Data data; private: // Assuming the constructor is private // So that you have to use Stream::asFile() to construct // a stream object. Stream(std::string const& name) : data{name} {} public: // Here is your static function. static Stream asFile(std::string const& name) { return Stream(name); } // Need a public Move Constructor. Stream(Stream&& move) : data(std::move(move.data)) {} }; // Two versions of parse. // One takes a stream by reference. // And does the work. void parse(Stream& stream) { std::cout << " Parsing Stream\n"; } // A version of parse that takes an r-value reference. // Here you take ownership of the stream but simply // call the standard version of parse (above). void parse(Stream&& stream) { std::cout << " Parsing Moved Stream\n"; parse(stream); }; // Test Framework that shows both operations. int main() { std::cout << "Parse using reference\n"; Stream file = Stream::asFile("filename.txt"); parse(file); // file.stuff() file still own the resource // You can call normal methods on it. std::cout << "Parse using r-value reference\n"; parse(Stream::asFile("filename.txt")); // This one moves the ownership to the second parse. } Running: Parse using reference Parsing Stream Parse using r-value reference Parsing Moved Stream Parsing Stream
73,116,578
73,116,655
Function pointer inside class point to that class's member function
I am familiar with the function pointer to class member issue, which requires the signature to be ClassName::*FuncPtr, but I have this nuanced problem where I need the function pointer to be to a containing class member: class F { public: class Container; typedef void (Container::*FuncPtr)(); F(FuncPtr fp) : m_fp(fp) {} void Execute() { (*this.*m_fp)(); } private: FuncPtr m_fp; }; class Container { public: Container() : fps(&Container::Func) { } void Func() { } private: F fps; }; So, basically I want to create an object Container, which will send in its constructor a pointer to one of its member functions to the F object it contains, which should store that function pointer.
You need to move the forward declaration class Container; outside of F. Inside of F, it is declaring F::Container, which is a different type than Container. Also, (*this.*m_fp)() (alternatively (this->*m_fp)()) won't work at all, as m_fp is expecting a Container object on the left side of .* (or ->*), but this is pointing at an F object instead. So Container will have to pass its this pointer to F's constructor to be stored along with m_fp. Try this: #include <iostream> using namespace std; class Container; class F { public: typedef void (Container::*FuncPtr)(); F(Container &c, FuncPtr fp) : m_c(c), m_fp(fp) {} void Execute() { (m_c.*m_fp)(); } private: Container& m_c; FuncPtr m_fp; }; class Container { public: Container() : fps(*this, &Container::Func) { } void Func() { ... } private: F fps; }; Online Demo
73,117,085
73,117,112
Why does the program work after removing the symbol information?
I made one SO file and compiled it with a compile option called "-Xlinker --strip-all " to counter any reverse engineering (use clang). Thanks to this, most of the symbols of functions other than functions directly exposed to the outside do not appear (objdump -TC test.so). The question is, if a symbol is deleted like this, it should not be used inside the program, so I think it is normal. What am I missing?
You're right, debugging symbols aren't needed by the program itself to execute; the linker computes (and therefore knows at link-time) what the memory-address of each function/global-variable/etc will be at run-time, so it can just place that memory-address directly into the executable where necessary. The symbols are there for a debugger to use, to make the debugging output easier for a human (or a debugging tool) to use and understand.
73,117,349
73,117,805
managing global state with parameterization (without singleton) but with a templated class
I am writing a small pub/sub application in c++14/17 for practice and self-learning. I say 14/17 because the only feature of c++17 I have used for this project so far has been the std::scoped_lock. In this toy application, the publishers and subscribers are on the same OS process (same compiled binary). A reasonable thing is to do in this case, is have a single class that stores the messages in an std::unordered_map<std::string, std:enque>. I plan on instantiating this class in main and passing it to the constructors of the publishers and subscribers. The problem comes when I attempt to hold the messages into a custom queue class, with a template for different messages; for example using protobuf. Please consider the following: // T here represents different // protobuf classes template <class T> class Queue { public: std::mutex mutex_; void enqueueMessage(const T* message); const T* dequeueMessage(); const int length() { return messages_.size();}; private: std::string id_; std::deque<const T*> messages_; }; class Node { public: Node(); template <class T> Publisher<T>* createPublisher(std::string const topic_name, Broker broker); }; class Broker { public: template <class T> Publisher<T>* createPublisher(std::string const topic_name); private: /** THE PROBLEM IS HERE **/ std::unordered_map<std::string, Queue<T*>*> queues_; }; int main(int argc, char** argv) { // this object holds the global state // and will be passed in when needed auto broker = std::make_shared<Broker>(); EmployeeMessage empMessage = EmployeeMessage(/* params */); WeatherMessage weatherMessage = WeatherMessage(/* params */); auto nodeEmp = std::make_shared<Node>(); auto nodeWeather = std::make_shared<Node>(); nodeEmp.createPublisher<EmployeeMessage>("name1", broker); nodeWeather.createPublisher<EmployeeMessage>("name2", broker); } The queues_ member of the Broker class cannot have a Type T because the Broker is not a template class. I cannot make Broker into a template class because then I would have an instance of broker for each type of message. How can I fix this design?
Use a base class QueueBase and stores the base class pointers. struct QueueBase { virtual ~QueueBase() {} }; template <class T> class Queue: QueueBase {}; class Broker { private: std::unordered_map<std::string, QueueBase*> queues_; }; When you need access queues_, dynamic_cast to the type you want. e.g. class Broker { template <typename T> Queue<T>* get(const std::string& topic_name) { return dynamic_cast<Queue<T*>>(queues_.at(topic_name)); } }; This's just a case, pay attention to expcetion safety and error handling.
73,118,134
73,118,213
C++ template class error: function returning a function
I want to make a simple logger which automatically runs a function and returns its value. The class is defined as: template <typename R, typename... Args> class Logger3 { Logger3(function<R(Args...)> func, const string& name): func{func}, name{name} {} R operator() (Args ...args) { cout << "Entering " << name << endl; R result = func(args...); cout << "Exiting " << name << endl; return result; } function<R(Args...)> func; string name; }; I want to pass the following simple add function to the logger: int add(int a, int b) { cout<<"Add two value"<<endl; return a+b; } By calling it this way: auto caller = Logger3<int(int,int)>(add,"test"); However, it generates the following errors: error: function returning a function 133 | Logger3(function<R(Args...)> func, | ^~~~~~~ decorator.h:138:7: error: function returning a function 138 | R operator() (Args ...args) | ^~~~~~~~ decorator.h:145:26: error: function returning a function 145 | function<R(Args...)> func;
There are 3 issues in your code: The Logger3 class template requires R to be the return value of the function (and Args it's arguments). (R is not a function type as implied by your attempt to instantiate Logger3). Therefore instantiating the Logger3 in your case of a function that gets 2 ints and returns an int should be: auto caller = Logger3<int, int, int>(add, "test"); Your Logger3 constructor should be public in order to invoke it from outside the class. For efficiency reasons, you should use std::forward to forward the arguments from operator() to your function. This will avoid copy of the arguments (more significant in cases where their types are more complex than ints). Note that in order for std::forward to work as expected, operator() has to be itself a variadic template using forwarding references (see below). Complete fixed version: #include <string> // std::string #include <functional> // std::function #include <utility> // std::forward, std::declval #include <iostream> // std::cout template <typename R, typename... Args> class Logger3 { public: Logger3(std::function<R(Args...)> func, const std::string& name) : func{ func }, name{ name } {} // Template with forwarding references to avoid copies // 'typename' arg is for SFINAE, and only enables if a // function accepting 'Args...' can evaluate with 'UArgs...' template <typename...UArgs, typename = decltype(std::declval<R(*)(Args...)>()(std::declval<UArgs>()...))> R operator() (UArgs&&...args) { std::cout << "Entering " << name << std::endl; R result = func(std::forward<UArgs>(args)...); std::cout << "Exiting " << name << std::endl; return result; } private: std::function<R(Args...)> func; std::string name; }; int add(int a, int b) { std::cout << "Add two value" << std::endl; return a + b; } int main() { auto caller = Logger3<int, int, int>(add, "test"); auto res = caller(3, 4); std::cout << "result: " << res << std::endl; return 0; } Output: Entering test Add two value Exiting test result: 7 Demo: Godbolt. A side note: better to avoid using namespace std - see here: Why is "using namespace std;" considered bad practice?.
73,118,274
73,124,432
Making boost::spirit::hold_any accept vectors
According to its author @hkaiser, here boost::spirit::hold_any is a more performant alternative to boost::any and can, for the most part, be used as a drop-in replacement for the latter. I'm interested in it since it purports to allow for easy output streaming, a feature that boost::any lacks. While I'm able to input simple types like int into hold_any, I can't seem to get it to hold a container such as std::vector<int> for example. Here'e the code #include <iostream> #include <boost/spirit/home/support/detail/hold_any.hpp> // v1.79 #include <vector> using any = boost::spirit::hold_any; int main() { int a1 = 1; any v1(a1); // OK std::cout << v1 << std::endl; // OK std::vector<int> w2 = {5,6}; any v2(w2); // compilation error - invalid operands to binary expression ('std::basic_istream<char>' and 'std::vector<int>') std::cout << v2 << std::endl; } which fails to compile with hold_any.hpp:155:23: error: invalid operands to binary expression ('std::basic_istream<char>' and 'std::vector<int>') i >> *static_cast<T*>(*obj); Presumably, the std::vector<int> needs to be made istream streamable though I'm not sure how to proceed. How does one make this work?
Firstly, that advice is 12 years old. Since then std::any was even standardized. I would not assume that hold_any is still the better choice (on the contrary). Also, note that the answer you implied contains the exact explanation: This class has two differences if compared to boost::any: it utilizes the small object optimization idiom and a couple of other optimization tricks, making spirit::hold_any smaller and faster than boost::any it has the streaming operators (operator<<() and operator>>()) defined, allowing to input and output a spirit::hold_any seemlessly. (emphasis mine) Incidentally, the whole question was about streaming any in the first place, so the answer was on-point there. The code further drives home the assumption: // these functions have been added in the assumption that the embedded // type has a corresponding operator defined, which is completely safe // because spirit::hold_any is used only in contexts where these operators // do exist template <typename Char_> friend inline std::basic_istream<Char_>& operator>> (std::basic_istream<Char_>& i, basic_hold_any<Char_>& obj) { return obj.table->stream_in(i, &obj.object); } template <typename Char_> friend inline std::basic_ostream<Char_>& operator<< (std::basic_ostream<Char_>& o, basic_hold_any<Char_> const& obj) { return obj.table->stream_out(o, &obj.object); } So, indeed that explains the requirement. It's a bit unfortunate that the implementation is not SFINAE-ed so that you'd only run into the limitation if you used the stream_in/stream_out operations, but here we are.