question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
69,313,891
69,315,133
C++ open folder and fetch for subfolder
I'm finding a way to fetch all the subfolders in a known folder, and open them, then keep finding all the subfolders in that folder, keep opening them until there aren't any subfolders left more, then move to another folder in C++. Thanks for help!
Following up on Serge Ballesta's comment. If you can compile c++17, then make use of std::filesystem. This SO provides a solution to 'LS' a specific dir. Need to add recursion. However, if you are not able to run c++17, then you need to consider the OS you are working on. If Linux and using GCC, use native "dirent.h" SO post with solution. Just need to #include dirent.h If Windows, can use either windows.h or use a popular libarary extension of dirent.h for windows. If using windows.h native methods, here is a SO post with solution. If using windows extended dirent.h. Here is the github link. Just need to grab the header and add to your project. Can be nicer if working cross platform I just used this on my project, and was very convenient and easy.
69,314,116
69,325,936
Why Python complains when called method of pybind11 type_cast-ed class that derives from C++ std::vector?
Using pybind11 I wrap a C++ lib that I cannot modify. An issue came from a class that derives from std::vector. (Notes: This my first pybind11 project. I am not 'fluent' in Python. I was looking for solution on the web but without success.) Intro. Instance of E carries error data. E could be instantiated only by Es - a collector. Es gets enlarged with new instances of E by method(s) like addFront(...) while returning back from failed method(s) (i.e unwinding the call stack). Minimalistic source code: #include <pybind11/pybind11.h> #include <pybind11/stl.h> namespace py = pybind11; using namespace pybind11::literals; // Classes enum class ID { unknown, wrongParam }; class E { public: ID GetID() const { return id; } protected: E( ID _id ) { id = _id; }; ID id; friend class Es; }; class Es : public std::vector< E > { public: Es() {} Es( ID _id ) { push_back( E( _id ) ); } Es& addFront( ID _id ) { insert( begin(), E( _id ) ); // Base class methods! return *this; } }; Since derived from std::vector, as I learned, a type_caster for Es should be applied so it can be used as a list on Python side: namespace pybind11 { namespace detail { template <> struct type_caster< Es > : list_caster< Es, E > {}; }} // namespace pybind11::detail The pybind11 part is: void Bind( py::module_& m ) { py::enum_< ID >( m, "ID" ) .value( "unknown", ID::unknown ) .value( "wrongParam", ID::wrongParam ); py::class_< E >( m, "E" ) .def( "GetID", &E::GetID ); py::class_< Es >( m, "Es" ) .def( py::init<>() ) .def( py::init< ID >(), "id"_a ) .def( "addFront", &Es::addFront ); } When this Python code is executed: from AWB import ID, E, Es es = Es( ID.wrongParam ) es.addFront( ID.unknown ) python complains: E:\Projects\AWB>py Python 3.8.10 (tags/v3.8.10:3d8993a, May 3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from AWB import ID, E Es >>> es = Es( ID.wrongParam ) >>> es.addFront( ID.unknown ) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: addFront(): incompatible function arguments. The following argument types are supported: 1. (self: List[AWB.E], arg0: AWB.ID) -> List[AWB.E] Invoked with: <AWB.Es object at 0x000000000260CEB0>, <ID.unknown: 0> >>> Q: What I am doing wrong? Q: Why arg0: AWB.ID is incompatible with ID.unknown? Q: Maybe the type casting should be more precise? Well, in real world, I don't expect the Es will enlarge on Pyhon side. Mostly, I would need to export the collection (in human readble manner) what the Es has collected so far (on the C++ side). But since I am writting a test case - I need to be sure it works. Q: Even if it is possible, to use addFront, on Python side, to add an item into C++ std::vector... Would it be automatically visible in the Python's list?
Since you want to use C++ member functions specific to Es, I think you shouldn't try to use type-casting in this case. If you would type-cast Es, that means your Python type will be a copied list of E objects but it wouldn't have methods like addFront - you'll have append etc. What you can do is to wrap your type as an opaque type, and export the methods you need. This example is from the pybind11 documentation: py::class_<std::vector<int>>(m, "IntVector") .def(py::init<>()) .def("clear", &std::vector<int>::clear) .def("pop_back", &std::vector<int>::pop_back) .def("__len__", [](const std::vector<int> &v) { return v.size(); }) .def("__iter__", [](std::vector<int> &v) { return py::make_iterator(v.begin(), v.end()); }, py::keep_alive<0, 1>()) /* Keep vector alive while iterator is used */ // ....
69,314,747
69,314,772
Robotics code not working right, giving redefinition of main error
This is my first time working on c++ and I have no idea how to fix this, I've asked around for a while but got no answer. Deleting either of the int main() will cause an error, I also tried putting void and that didn't work. error shown: Redefinition of 'main' (63, 5) #include "vex.h" // Allows for easier use of the VEX Library using namespace vex; float myVariable; // "when Controller1 Axis3 changed" hat block void onevent_Controller1Axis3Changed_0() { Motor1.setVelocity(Controller1.Axis3.position(), percent); Motor2.setVelocity(Controller1.Axis3.position(), percent); Motor1.spin(forward); Motor2.spin(forward); } // "when Controller1 Axis2 changed" hat block void onevent_Controller1Axis2Changed_0() { Motor11.setVelocity(Controller1.Axis2.position(), percent); Motor12.setVelocity(Controller1.Axis2.position(), percent); Motor11.spin(forward); Motor12.spin(forward); } int main() { // register event handlers Controller1.Axis3.changed(onevent_Controller1Axis3Changed_0); Controller1.Axis2.changed(onevent_Controller1Axis2Changed_0); wait(15, msec); // post event registration // set default print color to black printf("\033[30m"); // wait for rotation sensor to fully initialize wait(30, msec); } // ---- START VEXCODE CONFIGURED DEVICES ---- // Robot Configuration: // [Name] [Type] [Port(s)] // Controller1 controller // Motor1 motor 1 // Motor2 motor 2 // Motor11 motor 11 // Motor12 motor 12 // ---- END VEXCODE CONFIGURED DEVICES ---- #include "vex.h" using namespace vex; int main() { // Initializing Robot Configuration. DO NOT REMOVE! vexcodeInit(); }
You have two main functions in your code. You must have only one. Either this one: int main() { // Initializing Robot Configuration. DO NOT REMOVE! vexcodeInit(); } Or this one: int main() { // register event handlers Controller1.Axis3.changed(onevent_Controller1Axis3Changed_0); Controller1.Axis2.changed(onevent_Controller1Axis2Changed_0); wait(15, msec); // post event registration // set default print color to black printf("\033[30m"); // wait for rotation sensor to fully initialize wait(30, msec); } EDIT: As mentioned in the comments, move this line: vexcodeInit(); into the first main of your code and delete the second main. Your final file should look something like this: #include "vex.h" // Allows for easier use of the VEX Library using namespace vex; float myVariable; // "when Controller1 Axis3 changed" hat block void onevent_Controller1Axis3Changed_0() { Motor1.setVelocity(Controller1.Axis3.position(), percent); Motor2.setVelocity(Controller1.Axis3.position(), percent); Motor1.spin(forward); Motor2.spin(forward); } // "when Controller1 Axis2 changed" hat block void onevent_Controller1Axis2Changed_0() { Motor11.setVelocity(Controller1.Axis2.position(), percent); Motor12.setVelocity(Controller1.Axis2.position(), percent); Motor11.spin(forward); Motor12.spin(forward); } // ---- START VEXCODE CONFIGURED DEVICES ---- // Robot Configuration: // [Name] [Type] [Port(s)] // Controller1 controller // Motor1 motor 1 // Motor2 motor 2 // Motor11 motor 11 // Motor12 motor 12 // ---- END VEXCODE CONFIGURED DEVICES ---- int main() { // Initializing Robot Configuration. DO NOT REMOVE! vexcodeInit(); // register event handlers Controller1.Axis3.changed(onevent_Controller1Axis3Changed_0); Controller1.Axis2.changed(onevent_Controller1Axis2Changed_0); wait(15, msec); // post event registration // set default print color to black printf("\033[30m"); // wait for rotation sensor to fully initialize wait(30, msec); }
69,315,201
69,315,402
Lambda Expression returning a bool flag not stopping condition variables wait() function
I have a WorkDispatcher class which holds Worker class objects as properties and launches their function in new threads. Here is a example: WorkDispatcher.h: class WorkDispatcher { private: std::thread m_reconstructionThread; std::shared_ptr <Reconstruction::RGBDImageModel> m_currentRGBD; public: WorkDispatcher(); std::mutex m_rgbdMutex, m_commandMutex; std::deque<Network::NetworkCommandModel> m_CommandQueue; std::condition_variable m_RgbConditional, m_CommandConditional; Reconstruction::SceneReconstructor m_Reconstructor; void Initialize(); void Work(); void Stop(); }; WorkDispatcher.cpp: void WorkDispatcher::Work() { m_reconstructionThread = std::thread( &Reconstruction::SceneReconstructor::Reconstruct, std::ref(m_Reconstructor), std::ref(m_currentRGBD), std::ref(m_CommandQueue), std::ref(m_rgbdMutex), std::ref(m_RgbConditional), std::ref(m_commandMutex), std::ref(m_CommandConditional) ); } These functions hold infinite loops and I use the condition variables to wait until work is avaible. For example my Reconstruct function: void SceneReconstructor::Reconstruct( std::shared_ptr<RGBDImageModel>& currentImage, std::deque<Network::NetworkCommandModel> commandQueue, std::mutex& rgbdMutex, std::condition_variable& rgbdCond, std::mutex& commandMutex, std::condition_variable& commandConditional) { while (true) { std::unique_lock<std::mutex> rgbdLocker(rgbdMutex); rgbdCond.wait(rgbdLocker, [this] {return m_QuitReconstructionFlag; }); // Quit flag to break out of loop if (m_QuitReconstructionFlag) break; // do stuff here } } So far so good, however if I want to quit the application I need to quit all of my worker threads. As seen above, for this these classes have a flag to quit, which I uses as follows: void WorkDispatcher::Stop() { // for all worker threads do this m_Reconstructor.m_QuitReconstructionFlag = true; if (m_reconstructionThread.joinable()) m_reconstructionThread.join(); } In theory this should stop the wait() function within a worker threads loop and then break out of the loop with the m_QuitReconstructionFlag, however this doesn't work. What does work is the following: remove the lambda from the wait functions call notify_all() on the condition variables after settings the quit-flags to true; This works fine for me, however the question is, why doesn't the lambda work?
why doesn't the lambda work? It works just fine, by itself. However, C++ requires complex rules to be followed to properly synchronize multiple execution threads. Just because one execution thread sets a particular variable to a value does not guarantee you, in any way, that other execution threads will see the variable's new value. The synchronization rules govern that behavior. So, this lambda works just fine. In its own execution thread. But if you want this lambda to observe changes to the value, made by other execution threads, this must be correctly synchronized. Additionally, if you review your documentation of wait(), you should find a detailed explanation that says that if the condition function evaluates to false, it will not be called again until the condition variable is notified. What does work is ... call notify_all() Well, of course. Since wait() requires the condition variable to be notified, before it checks the waited-on condition again, then that's what you must do! Finally, notifying the condition variable will work correctly in most cases, but, as I mentioned, synchronization rules (of which mutexes and condition variables play an important part of) have some edge cases where this, by itself, will not work. You must follow the following sequence of events strictly in order to have proper synchronization in all edge cases: Lock the same mutex that another execution thread has locked before waiting on its condition variable. Notify the condition variable. Unlock the mutex
69,315,273
69,316,613
Process of conversion of types inside selection and iteration statements in C++
According To C++ ISO: The value of a condition that is an initialized declaration in a statement other than a switch statement is the value of the declared variable contextually converted to bool (7.3). If that conversion is ill-formed, the program is ill-formed. The value of a condition that is an initialized declaration in a switch statement is the value of the declared variable if it has integral or enumeration type, or of that variable implicitly converted to integral or enumeration type otherwise. The value of a condition that is an expression is the value of the expression, contextually converted to bool for statements other than switch; if that conversion is ill-formed, the program is ill-formed. The following quote comes from the section 7.3 said above: Certain language constructs require that an expression be converted to a Boolean value. An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t (9.4). Based on these two, I got an idea that switch-statement not always conducts conversions if it has the appropriate type. Otherwise if-statement looks to always perform such conversion, even if I do something like if (true){},I understood the true value would be converted. So, is it what happens? The code: if(true){} will convert true to boolean?(even true already being a boolean)
Comments already discussed that you are misinterpreting the two paragraphs. I will focus on the second. The important message is the following: There are certain contexts where values might implicitly undergo converions even though the conversion is actually only possible explicitly. Some code examples might help: struct foo{ explicit operator bool() {return true;} }; int main() { foo f; bool b(f); // fine ! bool c = f; // error! no viable conversion from f to bool // because foo::operator bool is explicit } A foo can be converted to a bool but the conversion operator is explicit. Hence bool b(f) (explicit conversion) is fine, while bool c = f; (implicit conversion) is not. Now, there are certain contexts where... An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t (9.4). This explains some special case of conversions. Such conversion happen implicitly, but are well-formed exactly when the explicit conversion would be well formed. With out such "contextual conversion", this would be a compiler error: foo f; if (f) {} However, because f is contextually convertible to bool, the code is ok. Without this special rule for contextual conversion one would have to write if (bool(f)) because foo::operator bool is explicit. In other words, the paragraph is not about bools getting converted to bool, but rather it explains an exception from the usual implicit / explicit conversions, that are applied when necessary.
69,315,783
69,327,913
Replace wildcards in a binary string avoiding three identical consecutive letters
Given a string S of length N, return a string that is the result of replacing each '?' in the string S with an 'a' or a 'b' character and does not contain three identical consecutive letters (in other words, neither 'aaa' not 'bbb' may occur in the processed string). Examples: Given S="a?bb", output= "aabb" Given S="??abb", output= "ababb" or "bbabb" or "baabb" Given S="a?b?aa", output= "aabbaa" 1<=n<= 500000 I solved the problem using backtracking, but my solution is slow and won't work for greater N values, is there a better approach?
Possible Implementation for rules in my answer. This implementation is left-to-right single pass with 2 look-behind and 1 look-ahead (despite initial checking) O(n) time complexity can be O(1) space complexity since the context is at most 4 character does not check for invalid Input First merge the rules a?? => ab? a??b => abab (a??b => ab?b => abab) a??a => abba a???????????????????b => ab??????????????????b ba?b => baab ^a?b => ^aab a? => ab otherwise (also imply a??) aa? => aab a?a => aba aa?b => aabb Then setup the boundary conditions. The rule need the string not start with ?s (not necessary if simply fill them in another pass) ^?? => a? (as if we prepend a b) ^?a => ba The rule need 2 look back in case of a?b so I simply pre-apply it to prevent the check inside primary loop prefill ^a?b => ^aab The Code (WandBox link) char inverse(char c){return c=='a'?'b':'a';} std::string solve(std::string s){ /// boundary conditions if(s.size()<3){ for(auto& c:s) if(c=='?') c='b'; return s; } if(s.starts_with("??")) s[0]='a'; // ?? => a? // not really necessary if use another pass to fill prefix '?'s if(s.starts_with("?a") || s.starts_with("?b")) s[0]=inverse(s[1]); // ?a => ba // not really necessary as above if(s.starts_with("a??") || s.starts_with("b??")) s[1]=inverse(s[0]); // not really necessary, just to prevent access s[-1] if(s.starts_with("a?b") || s.starts_with("b?a")) s[1]=s[0]; // ^a?b => aab /// primary loop for(auto curr=s.data(); curr!=s.data()+s.size(); ++curr) if(*curr=='?'){ if(curr[-1]!=curr[1] && curr[-2]==curr[1]) *curr=curr[-1]; // ba?b => baab else *curr = inverse(curr[-1]); // a? => b (rule coaslesing) } return s; }
69,315,914
69,351,512
Cmake - I have to run cmake --build . twice for a binary to be build
I have a problem with Conan and Cmake: With conan i'm downloading my libraries and i want to compile with Cmake, here is my CMakeLists.txt : cmake_minimum_required(VERSION 3.16) project(BABEL) set(CMAKE_CXX_STANDARD 20) set(PROJECT_NAME BABEL) set(SOURCES qt/main.cpp) include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake) include(${CMAKE_BINARY_DIR}/conan_paths.cmake) conan_basic_setup(KEEP_RPATHS) if (APPLE) set(CMAKE_INSTALL_RPATH "@executable_path/../lib") endif (APPLE) file(WRITE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/qt.conf [Paths]\nPrefix=${CONAN_QT_ROOT}) add_executable(${PROJECT_NAME} ${SOURCES}) find_package(portaudio REQUIRED) find_package(opus REQUIRED) find_package(Qt5 COMPONENTS Widgets Network Core Gui REQUIRED) target_link_libraries(${PROJECT_NAME} ${CONAN_LIBS}) target_link_libraries(${PROJECT_NAME} opus) if (WIN32) target_link_libraries(${PROJECT_NAME} portaudio_x64) else() target_link_libraries(${PROJECT_NAME} portaudio) endif() if I write this command : mkdir build && cd build && conan install .. && cmake .. -G "Unix Makefiles" && cmake --build. I'll have to write cmake --build . a second time for the binary to be built, any idea of what i did wrong here ? edit Here is the result of the build : -- Configuring done -- Generating done -- Build files have been written to: /Users/laurent/Documents/Delivery/Tek3/CPP/B-CPP-500-LYN-5-1-babel-kevin.melinon/build -- Conan: Adjusting output directories -- Conan: Using cmake global configuration -- Conan: Adjusting language standard -- Current conanbuildinfo.cmake directory: /Users/laurent/Documents/Delivery/Tek3/CPP/B-CPP-500-LYN-5-1-babel-kevin.melinon/build -- Conan: Using autogenerated Findportaudio.cmake -- Library portaudio found /Users/laurent/.conan/data/portaudio/19.7.0/bincrafters/stable/package/22e8f592c814313580425adf77089996d9853e39/lib/libportaudio.dylib -- Found: /Users/laurent/.conan/data/portaudio/19.7.0/bincrafters/stable/package/22e8f592c814313580425adf77089996d9853e39/lib/libportaudio.dylib -- Conan: Using autogenerated FindOpus.cmake CMake Warning (dev) at /usr/local/Cellar/cmake/3.21.3/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:438 (message): The package name passed to `find_package_handle_standard_args` (Opus) does not match the name of the calling package (opus). This can lead to problems in calling code that expects `find_package` result variables (e.g., `_FOUND`) to follow a certain pattern. Call Stack (most recent call first): build/Findopus.cmake:81 (find_package_handle_standard_args) CMakeLists.txt:24 (find_package) This warning is for project developers. Use -Wno-dev to suppress it. I can't put the full result.
So apparently there is a bug when writing all the command in one, typing them one by one solved the problem.
69,316,348
69,319,500
PyPy ephem couldn't install on linux
I want to install ephem package on PyPy 3.7 but i couldn't make it. Because i got following message during install. I guess, i'm missing something. gcc -pthread -DNDEBUG -O2 -fPIC -Ilibastro -I. -I/root/pypy3.7/include -c extensions/_libastro.c -o build/temp.linux-x86_64-3.7/extensions/_libastro.o -ffloat-store extensions/_libastro.c: In function ‘Body_repr’: extensions/_libastro.c:20:17: error: ‘Body’ {aka ‘struct <anonymous>’} has no member named ‘ob_base’; did you mean ‘ob_type’? #define OB_TYPE ob_base.ob_type ^~~~~~~ extensions/_libastro.c:1380:18: note: in expansion of macro ‘OB_TYPE’ body->OB_TYPE->tp_name, name, body); ^~~~~~~ extensions/_libastro.c:20:17: error: ‘Body’ {aka ‘struct <anonymous>’} has no member named ‘ob_base’; did you mean ‘ob_type’? #define OB_TYPE ob_base.ob_type ^~~~~~~ extensions/_libastro.c:1385:16: note: in expansion of macro ‘OB_TYPE’ body->OB_TYPE->tp_name, ^~~~~~~ extensions/_libastro.c:20:17: error: ‘Body’ {aka ‘struct <anonymous>’} has no member named ‘ob_base’; did you mean ‘ob_type’? #define OB_TYPE ob_base.ob_type ^~~~~~~ extensions/_libastro.c:1389:16: note: in expansion of macro ‘OB_TYPE’ body->OB_TYPE->tp_name, body); ^~~~~~~ error: command 'gcc' failed with exit status 1 PyPy info Python 3.7.10 (77787b8f4c49, May 15 2021, 11:50:33) [PyPy 7.3.5 with GCC 7.3.1 20180303 (Red Hat 7.3.1-5)]
After the Ronan Lamy answer, I changed the body->OB_TYPE with Py_TYPE(body) and it worked for v4.0.1
69,316,388
69,317,230
VSCode - custom snippet to create multiple different lines from selected C++ declaration
I have a line: int INTVAR; I would like to highlight this line, and run a snippet which automatically creates the following set of three lines in place of the single line above. int INTVAR; int intvar() {return INTVAR;} void intvar(int val){INTVAR = val;} That is, a function that it a getter/setter for the variable should automatically be generated. The variable name will always be in full capital letters. The getter/setter name should be the same except that they will always be in lower case. int could also be a double, char, etc. ETA: What I have tried/know so far: Instead of highlighting the line, the following appears more straightforward where I just type the declaration once and the getters/setters are automatically added. "int var set get":{ "prefix": "intsetget", "body":[ "int ${1:VARNM};", "int ${1:/downcase}(){return ${1};}", "void ${1:/downcase}(int val){${1} = val;}" ] } This almost gets the job done, except that the downcase for setter and getter name does not work.
The following snippet will also handle the different types: "var set get":{ "prefix": "varsetget", "body":[ "${1:int} ${2:VARNM};", "$1 ${2/(.*)/${1:/downcase}/}(){return $2;}", "void ${2/(.*)/${1:/downcase}/}($1 val){$2 = val;}" ] } I think it can be done with selected text but you have to insert the snippet with a key binding, otherwise there is no selected text for the snippet to use. But It might be easier to copy the var name and use the full snippet. Edit Better is to use different variable name convention (ALL CAPS usually means a constant). To support fMyVar, f_myVar, mMyVar and m_myVar member names you can use "var set get f m_":{ "prefix": "varsetgetfm", "body":[ "${1:int} ${2:VARNM};", "$1 ${2/^(?:f|m)_?([A-Za-z])(.*)|([A-Z].*)$/${1:/downcase}$2${3:/downcase}/}(){return $2;}", "void ${2/^(?:f|m)_?([A-Za-z])(.*)|([A-Z].*)$/${1:/downcase}$2${3:/downcase}/}($1 val){$2 = val;}" ] }
69,316,420
69,317,280
Boost module machine type 'X86' conflicts with target machine type 'x64'
I am building a 64bit program on Windows and need to link to a Boost library. I am using other 64bit libraries successfully. When I built boost I specified exactly that I need 64bit libraries using the command `.\b2 address-model=64' And it built the library I need: `libboost-serialization-vc120-mt-s-x64_1_77.lib' This should be a 64bit library as its name implies. However when I try to compile my program I get the linking error: Description: `error LINK1112: module machine type 'X86' conflicts with target machine type 'x64' File: `libboost-serialization-vc120-mt-s-x64_1_77.lib' What's going on - it is a 64bit library why is it saying that it conflicts with machine type 'x64' and what can I do about it?
Ok, I "figured out" how to get round this. Basically, what I thought was happening was happening. Despite specifying a 64bit build and those libraries getting the name appropriate to a 64bit build, they were being built using the 32bit tool-chain. To anyone from Boost who happens to see this - this is a REALLY bad experience and should be fixed To get it to build the libraries correctly I had to run a .bat script hidden away in the MSVC program files to set the environment to 64bit before the usual boost procedure. There are a variety of these scripts for different purposes as detailed here, although infuriatingly it doesn't specify where to find them. After hunting around for them I found the file I needed vcvarsx86_amd64.bat (for complicated reasons I'm using an old version of MSVC which only comes in a 32bit flavor but can cross-compile 64bit code). For me this was found in C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\x86_amd64\vcvarsx86_amd64.bat Note: for any of this to work this all has to be done inside a developer command prompt which for me was located at C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts Once in the that command prompt the proper library files were then built by typing C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\x86_amd64\vcvarsx86_amd64.bat bootstrap vc12 b2 address-model=64 Then it linked as expected. Disclaimer: Unnecessary opinion - feel free to edit this away... Coming from *nix environments, all of this seems terrible. Boost is essential to c++ development, but just getting it to build with MSVC is so incredibly contrived, opaque, and just... broken. Almost like it is designed to make it difficult. How do you put up with it?
69,316,446
69,316,543
Calling lambda with non-parameter template argument
MSVC 2019 allow me to define a lambda like this, where the template argument is not used in the parameter list: auto foo = []<bool B>() { return B; }; However, it gives syntax error when trying to call it like this? foo<false>(); What is the correct way to call a lambda with a non-parameter template argument?
The template parameter is used with operator() of lambda. (since C++20) If the lambda definition uses an explicit template parameter list, that template parameter list is used with operator(). You can specify the non-type template argument for operator(), call the lambda in an unnormal style as: foo.operator()<false>();
69,317,225
69,321,614
Doxygen not auto-linking to C++ function with argument list in an undocumented namespace
I am trying to generate a link to a specific version of a function by specifying the arguments. If I just use the plain function name fn() then Doxygen auto-links to one version of the function. If I include the arguments then no link is generated. Doxygen says I should be able to link using either of these forms: <functionName>"("<argument-list>")" <functionName>"()" https://www.doxygen.nl/manual/autolink.html The full example is shown below (Run.hpp): // Copyright (c) 2021 Graphcore Ltd. All rights reserved. /** \file * Functions for recurrent neural networks (RNN). */ #ifndef popnn_Rnn_hpp #define popnn_Rnn_hpp /** Create state tensor to be used in all recurrences of the RNN. * * TESTING: * * The default createOutputTensor() generates a link. But none of * the versions below do. * See createOutputTensor(int graph, const int params, * unsigned numShards, * const int debugContext) * * See createOutputTensor(int graph, const int params, * unsigned multiple, unsigned numShards, * const int debugContext) * * Or all on one line: createOutputTensor(int, const int, unsigned, unsigned, const int) * */ void createInitialState(); /** Create tensor. * * \param graph Graph object. * \param params The RNN parameters. * \param numShards The number of shards to be used. * \param debugContext Debug information. * * \return Tensor of shape {timeSteps, batchSize, outputSize}. */ void createOutputTensor(int graph, const int params, unsigned numShards, const int debugContext); /** Create tensor with size. * * \param graph Graph object. * \param params The RNN parameters. * \param multiple Integer multiple of standard output tensor. * \param numShards The number of shards to be used. * \param debugContext Debug information. * * \return Tensor of shape {timeSteps * multiple, batchSize, outputSize}. */ void createOutputTensor(int graph, const int params, unsigned multiple, unsigned numShards, const int debugContext); #endif // #ifndef popnn_Rnn_hpp Doxygen version and configuration: $ doxygen --version 1.9.2 $ doxygen -x # Difference with default Doxyfile 1.9.2 PROJECT_NAME = "Poplar and PopLibs" OUTPUT_DIRECTORY = ./doxygen INPUT = ./include GENERATE_LATEX = NO
Thanks to @albert I realised the function references need to be on a single line. But then I found another problem when I went back to the full version of the code. Turns out that the problem is caused by being in a namespace. The plain function name fn() is auto-linked to a version of the function. If the arguments are included then no link is generated. But if there is a namespace comment, then all versions of the function reference generate a link. The full example is shown below (Run.hpp): // Copyright (c) 2021 Graphcore Ltd. All rights reserved. /// Namespace comment needed to generate cross-references namespace rnn { /** Create state tensor to be used in all recurrences of the RNN. * * The default createOutputTensor() generates a link. But none of * the versions below do. * * See createOutputTensor(int graph, const int params, unsigned numShards, const int debugContext) * * See createOutputTensor(int graph, const int params, unsigned multiple, unsigned numShards, const int debugContext) * */ void createInitialState(); /** Create tensor. * * \param graph Graph object. * \param params The RNN parameters. * \param numShards The number of shards to be used. * \param debugContext Debug information. * * \return Tensor of shape {timeSteps, batchSize, outputSize}. */ void createOutputTensor(int graph, const int params, unsigned numShards, const int debugContext); /** Create tensor with size. * * \param graph Graph object. * \param params The RNN parameters. * \param multiple Integer multiple of standard output tensor. * \param numShards The number of shards to be used. * \param debugContext Debug information. * * \return Tensor of shape {timeSteps * multiple, batchSize, outputSize}. */ void createOutputTensor(int graph, const int params, unsigned multiple, unsigned numShards, const int debugContext); } // namespace rnn
69,317,311
69,317,794
Makefile cant find directories C++
I am working on a project related to Chess and I use a makefile to compile everything. My goal is to compile only files that have been changed,instead of everything everytime. Folder structure can be seen clearer here. make main.o results in an error : fatal error: chesspieces.h: No such file or directory 5 | #include "chesspieces.h" And pretty much everything else gives me a No rule to make target .o . Stop. I am using make from chess/src and I have every folder included in my Includes variable. Make file here: CC = g++ INCLUDES =-Icomponents -IBoard -Ipieces -IApplication OUTPUT = -o Chess Chess: main.o board.o player.o chess.o $(CC) main.o board.o player.o chess.o $(OUTPUT) main.o: main.cc board.h chess.h player.h chesspieces.h $(CC) $(INCLUDES) -c main.cc position.o: position.cc position.h $(CC) $(INCLUDES) -c position.cc piece.o: piece.cc piece.h color.h position.h $(CC) $(INCLUDES) -c piece.cc rook.o: rook.cc rook.h piece.h $(CC) $(INCLUDES) -c rook.cc queen.o: queen.cc queen.h piece.h $(CC) $(INCLUDES) -c queen.cc pawn.o: pawn.cc pawn.h piece.h $(CC) $(INCLUDES) -c pawn.cc knight.o: knight.cc knight.h piece.h $(CC) $(INCLUDES) -c knight.cc king.o: king.cc king.h piece.h $(CC) $(INCLUDES) -c king.cc bishop.o: bishop.cc bishop.h piece.h $(CC) $(INCLUDES) -c bishop.cc square.o: square.cc square.h color.h position.h $(CC) $(INCLUDES) -c square.cc board.o: board.cc board.h square.h position.h $(CC) $(INCLUDES) -c board.cc player.o: player.cpp player.h board.h piece.h $(CC) $(INCLUDES) -c player.cc chess.o: chess.cc chess.h player.h board.h piece.h $(CC) $(INCLUDES) -c chess.cc Making the dependencies my thinkings was to add every header included in the file,not sure about that EDIT: Compiling on command line works fine(Besides the linking errors) g++ -Icomponents -IBoard -IPieces -Iapplication main.cc So something is wrong with the $(INCLUDES) variable,can't figure out why but it's blank: g++ -c -o main.o main.cc main.cc:5:10: fatal error: chesspieces.h: No such file or directory Folders1 Folders2
The thing you didn't make clear in your question is the structure of your directory, or the directory you were in when you ran make. By reviewing the github repo we can see that your makefile is in the root directory and your source files are in subdirectories: for example you have src/main.cc, src/Application/chess.cc, etc. But in your makefile, you don't provide any paths. Your rules are: main.o: main.cc board.h chess.h player.h chesspieces.h $(CC) $(INCLUDES) -c main.cc These files you've mentioned here don't exist, so make will fail. I'm actually confused about how you're getting the behavior you are: you should get errors like, No rule to build main.cc or something like that. Maybe you're not running make in the root directory of your source tree, but rather somewhere else? In that case make can't find your makefile and it's just using default rules, which explains why your INCLUDES variable is not found.
69,317,427
69,317,590
C++ Must take either one or zero argument error (Operator+)
I have the following statement in my Hour.cpp file: (after class Hour) Hour Hour ::operator+(const Hour& h1, const Hour& h2) const{ return Hour(h1.getHour()+ h2.getHour(), h1.getMinute() + h2.getMinute(), h1.getSecond() + h2.getSecond()); } However, after running it I get: error: must take either zero or one argument
While overloading an operator as a member function, you can only another class as a second operand. The first operand is the object of the class itself. So, you have two options: You can modify the overloading function as Hour Hour::operator+(const Hour& h) const{ return Hour(hour_ + h.getHour(), minute_ + h.getMinute(), seconds_ + h.getSecond()); } where hour_, minute_, seconds_ are member variables of Hour class. Do not implement as a member function Hour operator+(const Hour& h1, const Hour& h2) const{ return Hour(h1.getHour()+ h2.getHour(), h1.getMinute() + h2.getMinute(), h1.getSecond() + h2.getSecond()); }
69,317,629
69,318,409
C/C++ recvmsg() causes error 'unaligned tcache chunk detected' but recv() is successful
I observe the below error when receiving UDP packets via Epoll: 'unaligned tcache chunk detected' I've managed to locate which part of the code but it doesn't make much sense. This is the original code: while (_listen) { const int count = epoll_wait(_epollFd, &events[0], MAX_SOCKETS, -1); assert(count != -1); for (int j = 0; j < count; ++j) { iovec iov; char control[1024]; msghdr msg; iov.iov_base = _buffer; iov.iov_len = sizeof(_buffer); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_namelen = sizeof(sockaddr_in); msg.msg_control = &control[0]; msg.msg_controllen = 1024; const int sock = events[j].data.fd; const int64_t n = recvmsg(sock, &msg, 0); // This line seems to cause the problem // More code } } _buffer is a class member declared as: char _buffer[65'536]; By trial and error I narrowed the problem to this line: const int64_t n = recvmsg(sock, &msg, 0); So I replaced ::recvmsg() with a call to ::recv() and it runs successfully: while (_listen) { const int count = epoll_wait(_epollFd, &events[0], MAX_SOCKETS, -1); assert(count != -1); for (int j = 0; j < count; ++j) { const int sock = events[j].data.fd; const int64_t n = recv(sock, _buffer, sizeof(_buffer), 0); // More code } } Now the problem doesn't occur. What is causing this? I'd like to understand why the first code doesn't work. The only memory is _buffer and that's not manually allocated. (Unfortunately I cannot use a sanitize build due to the environment/build system).
In your code you forgot to set member msg_name of the struct msg: iovec iov; char control[1024]; msghdr msg; // add the following line: sockaddr_in addr; iov.iov_base = _buffer; iov.iov_len = sizeof(_buffer); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = &control[0]; msg.msg_controllen = 1024; // set the following members: msg.msg_name = &addr; msg.msg_namelen = sizeof(addr); const int sock = events[j].data.fd; const int64_t n = recvmsg(sock, &msg, 0); // More code The reason you had memory corruption is because you had undefined behavior: recvmsg() tried to write to pointer msg.msg_name, but the latter contained an uninitialized memory address, so recvmsg() was actually writing to an invalid location. recvmsg() writes information about the host that sent the message inside msg.msg_name.
69,318,119
69,318,511
Generalizing input arguments for Eigen-types
The template guide provided by Eigen recommends using Eigen::MatrixBase to implicitly deduce template parameters to functions. In this example I want to pass an expression: #include <iostream> #include "Eigen/Dense" template <typename D> void eval(Eigen::MatrixBase<D>& in, Eigen::MatrixBase<D>& out) { out.array() = in.array() + 1; } int main() { Eigen::MatrixXd A(2,2); A(0,0) = 2; A(1,1) = 1; Eigen::VectorXd B(2); B(1) = 1; std::cout << A << ", " << B << std::endl; Eigen::VectorXd res(2); eval(A*B, res); std::cout << res << std::endl; } Which outputs an error: EigenTest.cpp: In function ‘int main()’: EigenTest.cpp:21:18: error: no matching function for call to ‘eval(const Eigen::Product<Eigen::Matrix<double, -1, -1>, Eigen::Matrix<double, -1, 1>, 0>, Eigen::VectorXd&)’ 21 | eval(A*B, res); Is there a more general form of Eigen::MatrixBase that extends to accepting expressions?
You have to use two template parameters and make the input reference refer to a const type. The issue is that the product operator will return a const value. Like this template <typename U, typename V> void eval(const Eigen::MatrixBase<U>& in, Eigen::MatrixBase<V>& out) { out.array() = in.array() + 1; }
69,318,879
69,319,138
process a string using regular expression with C++14
I need to extract 3 vars from a string in C++14. The string format is: a single uppercase char + `->` + a single uppercase char + `,` + a number For example: A->B,100, C->D,20000, E->F,22. And I want to extract both single uppercase chars and the number, like A, B, 100. So far I can write a tokenized function to separate them by calling tokenized() multiple times like this: vector<string> tokenize(const string& s, const char c) { vector<string> splitted; auto ss = stringstream(s); string tmp; while(getline(ss, tmp, c)) { splitted.push_back(tmp); } return splitted; } // ... t = tokenized(s, '') But I was wondering if there is a simpler way to extract these 3 variables using regex? I tried the \(A-Z.*?->\A-Z)\,\ but clearly I wrote the wrong regex.
With regexes in C++ there is one thing you need to know : you need to do the iteration over multiple matches yourself. Here's an example : #include <iostream> #include <regex> #include <string> #include <vector> //----------------------------------------------------------------------------- // if you're going to tokenize you might as well return tokens struct token_t { token_t(const std::string& f, const std::string& t, const unsigned long v) : from{ f }, to{ t }, value{ v } { } std::string from; std::string to; unsigned long value; }; std::ostream& operator<<(std::ostream& os, const token_t& token) { os << "token : from = " << token.from << ", to = " << token.to << ", value = " << token.value << std::endl; return os; } std::ostream& operator<<(std::ostream& os, const std::vector<token_t>& tokens) { std::cout << std::endl << "------------------ tokens ------------------" << std::endl; for (const auto& token : tokens) { os << token; } std::cout << "--------------------------------------------" << std::endl; return os; } //----------------------------------------------------------------------------- auto tokenize(const std::string& s) { static const std::regex rx{ "([A-Z])->([A-Z]),([0-9]+)" }; std::smatch match; std::vector<token_t> tokens; auto from = s.cbegin(); while (std::regex_search(from, s.cend(), match, rx)) { tokens.push_back({ match[1], match[2], std::stoul(match[3]) }); from = match.suffix().first; } return tokens; } //----------------------------------------------------------------------------- int main() { auto v1 = tokenize("A->B,100"); auto v2 = tokenize("A->B,100, C->D,2000, E->F,22"); std::cout << v1; std::cout << v2; return 0; }
69,319,035
69,319,421
How to use a shared_ptr from interface implementation
Let’s say that DoSomething method is the implementation of an interface. I can’t change its signature. How could DoSomething instantiate MyClass2 with the second constructor and provide a smart pointer to the current instance of MyClass (not a copy) ? #include <Windows.h> #include <iostream> class MyClass; class MyClass2 { public: std::shared_ptr<MyClass> ptr; MyClass2() { ptr = nullptr; } MyClass2(std::shared_ptr<MyClass> ptrParam) { ptr = std::move(ptrParam); } }; class MyClass { public: int value; MyClass() : value{1} { OutputDebugString(L"MyClass\r\n"); } ~MyClass() { OutputDebugString(L"~MyClass\r\n"); } std::shared_ptr<MyClass2> DoSomething() { return std::make_shared<MyClass2>(); } }; int main() { auto ptr = std::make_shared<MyClass>(); auto ptr2 = ptr->DoSomething(); }
The only way for this to work is if DoSomething has access to a smart pointer pointing to the instance of MyClass. You can't place a shared_ptr in MyClass because that would create a reference loop, creating a memory leak. However, there is another type of smart pointer: weak_ptr. It was designed for pretty much this purpose: when you need a smart pointer, but you don't want to create a reference loop. class MyClass { public: int value; std::weak_ptr<MyClass> selfReference; MyClass() : value{1} { OutputDebugString(L"MyClass\r\n"); } ~MyClass() { OutputDebugString(L"~MyClass\r\n"); } void giveSelfReference(std::shared_ptr<MyClass>& sr) { selfReference = sr; } std::shared_ptr<MyClass2> DoSomething() { return std::make_shared<MyClass2>(selfReference.lock()); } }; So, then main would look like: int main() { auto ptr = std::make_shared<MyClass>(); ptr->giveSelfReference(ptr); auto ptr2 = ptr->DoSomething(); } Edit: There is a comment recommending std::enable_shared_from_this<T>::shared_from_this, I'm not familiar with this, but it looks to be a somewhat more elegant version of my solution.
69,319,153
69,319,542
Iterator concepts are weaker than the corresponding named requirements, which ones apply to the non-range standard algorithms?
In C++20 we got concepts for iterator categories, e.g. std::forward_iterator corresponds to named requirement ForwardIterator. They are not equivalent. In some (but not all) regards, the concepts are weaker: (1) "Unlike the [ForwardIterator or stricter] requirements, the [corresponding] concept does not require dereference to return an lvalue." (2) "Unlike the [InputIterator] requirements, the input_iterator concept does not require equality_comparable, since input iterators are typically compared with sentinels." ... The new std::ranges algorithms seem to use the concepts to check iterator requirements. But what about the other standard algorithms? (that existed pre-C++20) Do they still use the same iterator requirements in C++20 as they were pre-C++20, or did the requirements for them get relaxed to match the concepts?
Do they still use the same iterator requirements in C++20 as they were pre-C++20, or did the requirements for them get relaxed to match the concepts? The existing std:: algorithms still use the named requirements. For instance, [alg.find] has both: template<class InputIterator, class T> constexpr InputIterator find(InputIterator first, InputIterator last, const T& value); and template<input_­iterator I, sentinel_­for<I> S, class T, class Proj = identity> requires indirect_­binary_­predicate<ranges::equal_to, projected<I, Proj>, const T*> constexpr I ranges::find(I first, S last, const T& value, Proj proj = {}); template<input_­range R, class T, class Proj = identity> requires indirect_­binary_­predicate<ranges::equal_to, projected<iterator_t<R>, Proj>, const T*> constexpr borrowed_iterator_t<R> ranges::find(R&& r, const T& value, Proj proj = {}); The same is true for all the algorithms. Note that there is a proposal to change this: Ranges views as inputs to non-Ranges algorithms. That paper would change the named requirements to become in line with the concepts (note that it would not change the std:: algorithms to accept sentinels).
69,319,268
69,319,355
What is the /d2vzeroupper MSVC compiler optimization flag doing?
What is the /d2vzeroupper MSVC compiler optimization flag doing? I was reading through this Compiler Options Quick Reference Guide for Epyc CPUs from AMD: https://developer.amd.com/wordpress/media/2020/04/Compiler%20Options%20Quick%20Ref%20Guide%20for%20AMD%20EPYC%207xx2%20Series%20Processors.pdf For MSVC, to "Optimize for 64-bit AMD processors", they recommend to enable /favor:AMD64 /d2vzeroupper. What /favor:AMD64 is doing is clear, there is documentation about that in the MSVC docs. But I can't seem to find /d2vzeroupper being mentioned anywhere in the internet at all, no documentation anywhere. What is it doing?
TL;DR: When using /favor:AMD64 add /d2vzeroupper to avoid very poor performance of SSE code on both current AMD CPUs and Intel CPUs. Generally /d1... and /d2... are "secret" (undocumented) MSVC options to tune compiler behavior. /d1... apply to complier front-end, /d2... apply to compiler back-end. /d2vzeroupper enables compiler-generated vzeroupper instruction See Do I need to use _mm256_zeroupper in 2021? for more information. Normally it is by default. You can disable it by /d2vzeroupper-. See here: https://godbolt.org/z/P48crzTrb /favor:AMD64 switch suppresses vzeroupper, so /d2vzeroupper enables it back. The up-to-date Visual Studio 2022 has fixed that, so /favor:AMD64 still emits vzeroupper and /d2vzeroupper is not needed to enable it. Reason: current AMD optimization guides (available from AMD site; direct pdf link) suggest: 2.11.6 Mixing AVX and SSE There is a significant penalty for mixing SSE and AVX instructions when the upper 128 bits of the YMM registers contain non-zero data. Transitioning in either direction will cause a micro-fault to spill or fill the upper 128 bits of all 16 YMM registers. There will be an approximately 100 cycle penalty to signal and handle this fault. To avoid this penalty, a VZEROUPPER or VZEROALL instruction should be used to clear the upper 128 bits of all YMM registers when transitioning from AVX code to SSE or unknown code Older AMD processor did not need vzeroupper, so /favor:AMD64 implemented optimization for them, even though penalizing Intel CPUs. From MS docs: /favor:AMD64 (x64 only) optimizes the generated code for the AMD Opteron, and Athlon processors that support 64-bit extensions. The optimized code can run on all x64 compatible platforms. Code that is generated by using /favor:AMD64 might cause worse performance on Intel processors that support Intel64.
69,319,480
69,320,030
Why do all my items go to unordered_map bucket 0?
This is the log (truncated) from my analysis of the hashmap: unsigned nbuckets = octree->Nodes.bucket_count(); LOG(Error, "bucket size = {0}, kk = {1}", nbuckets, octree->Nodes.max_load_factor()); for (auto& x : octree->Nodes) { LOG(Warning, "Element [{0}:{1}] is in bucket {2}", x.first.morton, x.second.position, octree->Nodes.bucket(x.first)); } [ 00:19:26.169 ]: [Error] bucket size = 512, kk = 1.0 [ 00:19:26.169 ]: [Warning] Element [132120576:X:384 Y:384 Z:384] is in bucket 0 [ 00:19:26.169 ]: [Warning] Element [115343360:X:128 Y:384 Z:384] is in bucket 0 [ 00:19:26.169 ]: [Warning] Element [98566144:X:384 Y:128 Z:384] is in bucket 0 [ 00:19:26.169 ]: [Warning] Element [81788928:X:128 Y:128 Z:384] is in bucket 0 [ 00:19:26.169 ]: [Warning] Element [65011712:X:384 Y:384 Z:128] is in bucket 0 [ 00:19:26.169 ]: [Warning] Element [48234496:X:128 Y:384 Z:128] is in bucket 0 [ 00:19:26.169 ]: [Warning] Element [31457280:X:384 Y:128 Z:128] is in bucket 0 [ 00:19:26.169 ]: [Warning] Element [16515072:X:192 Y:192 Z:192] is in bucket 0 [ 00:19:26.169 ]: [Warning] Element [14417920:X:64 Y:192 Z:192] is in bucket 0 [ 00:19:26.169 ]: [Warning] Element [12320768:X:192 Y:64 Z:192] is in bucket .... Map is defined like this: std::unordered_map<Int3Pos, OctreeNode, Int3Pos::HashFunction> Nodes; where OctreeNode is a struct with some values. And Int3Pos: struct Int3Pos // TODO rename { public: Int3_64 position; uint64 morton; Int3Pos() : position(Int3_64(0, 0, 0)), morton(0) { } Int3Pos(Int3_64 c) { this->position = c; this->morton = mrtn(this->position); } bool operator==(const Int3Pos& otherPos) const { if (this->morton == otherPos.morton) return true; else return false; } struct HashFunction { size_t operator()(const Int3Pos& pos) const { return pos.morton; } }; }; It tells 512 buckets, but all go to 0. Or I am misinterpreting something?
Your hash function is very bad. The greatest common divisor of the morton values you shown is GCD(132120576, 115343360, 98566144, 81788928, 65011712, 48234496, 31457280, 16515072, 14417920, 12320768) = 2^18 = 262144 It is divided by 512. All values go to the (first) bucket 0. You can try return pos.morton % 511; // or pos.morton % 1023, or std::hash<decltype(pos.morton)>{}(pos.morton).
69,319,600
69,319,643
How to extract one row of a 2D string vector to vector of double?
I have a function to calculate moving average: void MovingAverage(double inputSeries[] , size_t inputSize, size_t window, float* output ) My train of thought to do my calculation: construct a loop and extract one row of vec2D each time use the MovingAverage function to get output For the first step, the 2d-vector is parsed from a csv file: std::vector<std::vector<std::string>> vec2D{ {"S0001","01","02","03"}, {"S0002","11","12","13"}, {"S0003","21","22","23"} }; I want to extract one row of this 2D vector (say the 2nd) and store the row as a 1d vector std::vector<double> copyRow then calculate the moving average for each row. copyRow = {11,12,13} I tried vector<double> copyRow(vec2D[0].begin(), vec2D[0].end()); but it doesn't work because the 2D vector is std::string type. I also tried for loops: int rowN = vec2D.size(); int colN = vec2D[0].size(); double num; for (int i = 0; i < rowN; i++) { for (int j = 0; j < colN; j++) { num = stod(vec2D[i][j]); copyRow[i][j].push_back(num); } } But it appends all values from all rows into the vector. What would be the best way to do this?
I tried vector<double> copyRow(vec2D[0].begin(), vec2D[0].end()); but it doesn't work because the 2D vector is string type. You can make use of the algorithm function std::transform from <algorithm> to do this. Since the first element of each row cannot be transformed to a double , you can skip it by starting from one element after begin iterator: #include <algorithm> // std::transform std::vector<double> copyRow; // reserve memory for unwanted real locations copyRow.reserve(vec2D[1].size() - 1u); std::transform(std::cbegin(vec2D[1]) + 1, std::cend(vec2D[1]) , std::back_inserter(copyRow), [](const auto& ele) { return std::stod(ele); }); (See a Demo)
69,320,075
69,328,012
When is an ellipsis needed when dealing with parameter packs?
I'm trying to understand some code from cppreference.com. The relevant part is here template<typename... Ts> std::ostream& operator<<(std::ostream& os, std::tuple<Ts...> const& theTuple) { std::apply ( [&os](Ts const&... tupleArgs) { os << '['; std::size_t n{ 0 }; ((os << tupleArgs << (++n != sizeof...(Ts) ? ", " : "")), ...); os << ']'; }, theTuple ); return os; } If I'm interpretting the above correctly ((os << tupleArgs << (++n != sizeof...(Ts) ? ", " : "")), ...) is a fold-expression over the comma operator. Semantically it is([some pattern involving the parameter pack's values] , ...) which means to fold with comma. What I don't get however is why the sizeof in there is a sizeof...? To me ellipsis means expand, but we don't want to expand there. Ts is like an aggregate type, akin to a tuple, we just want the size at compile time of that aggregate type while the compiler evaluates the fold. And indeed in Visual Studio it works either way, with or without the ellipsis. Same in GCC, Godbolt tells me. (EDIT: actually I am wrong without the ellipsis it compiles but the output contains a trailing comma that should not be there) Is the rule to just always use sizeof... if you want the size of a parameter pack?
Ellipses are needed there because sizeof...(Ts) is a special form of sizeof that returns the size of a parameter pack. Ordinary sizeof(Ts) could not be used for this purpose because it needs to remain possible to use standard sizeof behavior in expanded patterns i.e. sizeof(Ts) returns the size of an individual type in an evaluated fold expression.
69,320,259
69,328,603
UE4 add Widget Class BP which inherits from UUserwidget in BP Editor?
I have a AActor class in cpp. I created a BP inherits from it named My_Actor_BP. In cpp class i declared some UPROPERTY : UPROPERTY(EditAnywhere, Category = "Event Section") TArray<UUserWidget*> Event_Dispatcher_0; UPROPERTY(EditAnywhere, Category = "Event Section") TArray<UUserWidget*> Event_Dispatcher_1; UPROPERTY(EditAnywhere, Category = "Event Section") TArray<UUserWidget*> Event_Dispatcher_2; UPROPERTY(EditAnywhere, Category = "Event Section") TArray<UUserWidget*> Event_Dispatcher_3; I want to contain some customized widgets in these. I have to say that, these customized widgets are all BP classes which inherits from different cpp classes. And these all different cpp classes inherits from UUserWidget class. In this way, my artist can implement his widget BPs. And i can use them in cpp functions. So far so good. When i check the "Event Section" in My_Actor_BP, and add a new element to Event_Dispatcher_0 array, element is adding but when i try to choose a asset there will be empty. No recommended BP's or anything. Probobly the reason of the zero recommendation is the type of the TArray's template type. When i created a BP class from directly UUserWidget, still no answer. What should be this type? Any advice would be great. Thanks in advance.
In the case where you want your user to specify the class of an object to be managed by another object, you want to use the TSubclassOf<> template. In the code above, you're asking the property to point to an actor, but that actor hasn't been created yet. What you want to do is point to the class, and you can then create the widget from that class in your Blueprint or native code. The source for GameModeBase.h gives good examples of this: /** HUD class this game uses. */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=Classes, meta = (DisplayName = "HUD Class")) TSubclassOf<AHUD> HUDClass;
69,320,288
69,320,345
Different ways of checking for a bit
quick question here... What is the difference between... if ((flags & bit1) == bit1) { // ... } and... if (flags & bit1) { // ... } ? That's all. Pretty sure this has been answered before, but I haven't been able to find it.
The first checks whether flags has all of the bits set where bit1 is also set. The second checks whether flags has any (i.e. at least one) of the bits set where bit1 is also set (or vice versa; in other words, whether there's any common set bits). If bit1 has a single bit set, then there is no difference between "any" and "all".
69,320,320
69,320,398
std::invoke does not like variadic template member functions?
I am trying to call a variadic function template using std::invoke() and std::apply(). And I apologize ahead of time, because I'm basically dropping a snippet of code here and asking someone to help me understand the error messages to solve the problem. So, in the example code below, std::invoke() on the non-variadic template functions works fine. std::invoke() on the variadic template function does not compile! #include <functional> #include <tuple> struct Thing { // Some simple functions to test things out int func0() { return 0; } int func1(int) { return 1; } int func2(int, int) { return 2; } // A variadic template function that causes problems below template<typename ...Args> int funcn(Args&&...) { return 99; } }; int main() { Thing thing; // These work fine std::invoke(&Thing::func0, thing); std::invoke(&Thing::func1, thing, 1); std::invoke(&Thing::func2, thing, 1, 2); // This one doesn't work std::invoke( &Thing::funcn, thing, 1, 2, 3, 4 ); } The errors I'm getting are here: (Output of x86-64 clang 12.0.1 (Compiler #1)) Wrap lines <source>:26:5: error: no matching function for call to 'invoke' std::invoke( ^~~~~~~~~~~ functional:94:5: note: candidate template ignored: couldn't infer template argument '_Callable' invoke(_Callable&& __fn, _Args&&... __args) ^
The std::invoke expect a callable function. The funcn is a function template, and you need to instantiate to get a real function out of it and there-by you can take the address of it. That means (explicitly) provide the template parameter to the function, how you want to instantiate it, so that std::invoke can see the function which it can invoke. std::invoke( &Thing::funcn<int, int, int, int>, // works now thing, 1, 2, 3, 4 );
69,320,322
69,320,820
Sorting array of objects in c++
I'm a newbie and this is my first question. So I am working for a task organizer and I want to organize list of tasks by their "urgency" value. Here is my code: #include <iostream> #include <math.h> #include <vector> #include <stdlib.h> #include <list> using namespace std; struct Task { public: string name; float deadline, estimated; int urgency; int getUrgency() { urgency = ceil(deadline - estimated); return urgency; } }; void newTask(Task task[], int n1) { for (int i = 0; i < n1; i++) { system("cls"); cout << "Input task name: "; cin >> task[i].name; cout << "Input task deadline (in hours): "; cin >> task[i].deadline; cout << "Input task estimated work time (in hours): "; cin >> task[i].estimated; } } void printAll(Task task[], int n1) { system("cls"); cout << "Name\tDeadline\tEstimated\tUrgency\n"; for (int i = 0; i < n1; i++) { cout << task[i].name << "\t" << task[i].deadline << "\t\t" << task[i].estimated << "\t\t" << task[i].getUrgency() << endl; } } int main() { int n; cout << "How many work do you have? "; cin >> n; //Create number of object based on input n std::vector<Task> p(n); newTask(p.data(), n); std::list<Task> taskList; printAll(p.data(), n); cin.ignore(); return 0; } I want to add a function that sorts the list of tasks by their "urgency" value. What kind of function should I use?
In your case you can use the std::sort function, defined in <algorithm> header, on the p vector defining a custom compare function: std::sort (p.begin(), p.end(), sortTaskByUrgency); where sortTaskByUrgency() is defined as: bool sortTaskByUrgency(const Task& lhs, const Task& rhs) { return lhs.getUrgency() < rhs.getUrgency(); } Using the above function in your sample code getUrgency() must be const: int getUrgency() const { return ceil(deadline - estimated); } removing useless int urgency public member.
69,320,400
69,320,704
Compare two numbers in a QString
There are two values: QString str1 = "3.5.8", str2 = "20.3.6"; Let's imagine that these two numbers represent the software version, as it were. It is known that QString compares character-by-character. What if we approach this decision in this way: str1.replace(".",""); str2.replace(".",""); int n = str1.toInt(); int m = str2.toInt(); if (n >= m) { qDebug() << "YES"; } else if (n <= m) { qDebug() << "NO"; } Maybe there is a more optimal and correct way to do this. Could you tell me please how I can translate these values into numbers so that they can be compared in their entirety. Thanks.
The QVersionNumber class was designed to solve this problem (requires Qt 5.6+): QVersionNumber version1 = QVersionNumber::fromString(str1); QVersionNumber version2 = QVersionNumber::fromString(str2); if (version1 > version2) { qDebug() << "YES"; } else { qDebug() << "NO"; }
69,320,703
69,320,774
Recording how much time is required to run a portion of code and store it to an array in C++
Need help in recording time taken to run several parts of code in C++. I need to store these times to an array for use later. In MATLAB I would do something like this; for i=1 : n tic this is some stuff I want to run(); array[1,i] = toc; tic this is some other stuff I want to run(); array[2,i] = toc; end The above would run 2 different things n times and store the time taken to individually run those things into a 2-D array. Is there something equivalent in C++?
You can use std::chrono::steady_clock::now() to get the current time (tic in your exemple). You can find more details in this answer. For a 2d array, a simple std::array<T, n> where T is some kind of std::tuple should do the trick.
69,320,918
69,321,080
Why does taking `istream&` to a temporary `stringstream` work, but not when taking `stringstream&`?
Consider the following code, it compiles and runs: #include <iostream> #include <sstream> struct Foo {}; void operator>>(std::istream &, Foo) { } int main() { std::stringstream{} >> Foo{}; } However, if I change std::istream to std::stringstream, I get an error: c.cpp: In function 'int main()': c.cpp:7:25: error: no match for 'operator>>' (operand types are 'std::stringstream' {aka 'std::__cxx11::basic_stringstream<char>'} and 'Foo') 7 | std::stringstream{} >> Foo{}; | ~~~~~~~~~~~~~~ ^~ ~~~~~ | | | | | Foo | std::stringstream {aka std::__cxx11::basic_stringstream<char>} c.cpp:4:6: note: candidate: 'void operator>>(std::stringstream&, Foo)' (near match) 4 | void operator>>(std::stringstream &, Foo) { | ^~~~~~~~ c.cpp:4:6: note: conversion of argument 1 would be ill-formed: c.cpp:7:10: error: cannot bind non-const lvalue reference of type 'std::stringstream&' {aka 'std::__cxx11::basic_stringstream<char>&'} to an rvalue of type 'std::stringstream' {aka 'std::__cxx11::basic_stringstream<char>'} 7 | std::stringstream{} >> Foo{}; | ^~~~~~~~~~~~~~ which makes sense: I cannot bind a lvalue reference to a rvalue (temporary) object. Why does the first code compile? UPD: my compiler is g++ (Rev2, Built by MSYS2 project) 10.3.0 Copyright (C) 2020 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. and flags are -std=gnu++17 -Wall -Wextra -Wshadow -O2 UPD2: at the very end there is an error regarding the operator which Brian Bi is talking about: In file included from C:/Software/msys64/mingw64/include/c++/10.3.0/iostream:40, from c.cpp:1: C:/Software/msys64/mingw64/include/c++/10.3.0/istream:980:5: note: candidate: 'template<class _Istream, class _Tp> typename std::enable_if<std::__and_<std::__not_<std::is_lvalue_reference<_Tp> >, std::__is_convertible_to_basic_istream<_Istream>, std::__is_extractable<typename std::__is_convertible_to_basic_istream<_Tp>::__istream_type, _Tp&&, void> >::value, typename std::__is_convertible_to_basic_istream<_Tp>::__istream_type>::type std::operator>>(_Istream&&, _Tp&&)' 980 | operator>>(_Istream&& __is, _Tp&& __x) | ^~~~~~~~ C:/Software/msys64/mingw64/include/c++/10.3.0/istream:980:5: note: template argument deduction/substitution failed: C:/Software/msys64/mingw64/include/c++/10.3.0/istream: In substitution of 'template<class _Istream, class _Tp> typename std::enable_if<std::__and_<std::__not_<std::is_lvalue_reference<_Tp> >, std::__is_convertible_to_basic_istream<_Istream>, std::__is_extractable<typename std::__is_convertible_to_basic_istream<_Tp>::__istream_type, _Tp&&, void> >::value, typename std::__is_convertible_to_basic_istream<_Tp>::__istream_type>::type std::operator>>(_Istream&&, _Tp&&) [with _Istream = std::__cxx11::basic_stringstream<char>; _Tp = Foo]': c.cpp:7:32: required from here C:/Software/msys64/mingw64/include/c++/10.3.0/istream:980:5: error: no type named 'type' in 'struct std::enable_if<false, std::basic_istream<char>&>'
As strange as it might seem, this code is well-formed. It should always compile. See Godbolt. It should also compile when the operator>> overload is changed to take std::stringstream&. The reason is that there exists a special rvalue operator>> overload for classes derived from std::ios_base, marked (3) here: template< class Istream, class T > Istream&& operator>>( Istream&& st, T&& value ); The effect is equivalent to: st >> std::forward<T>(value); return std::move(st); This is the operator>> overload that is called by your code. It delegates to the operator>> that you've written. (Because Foo is a member of the global namespace, unqualified name lookup will find your operator>> from any context thanks to ADL.) If you have a toolchain that doesn't have the rvalue stream extraction operator, then your code will not compile because, obviously, a non-const lvalue reference, Base&, will never bind to an rvalue of type Derived (where Derived is derived from Base). I don't know exactly why the rvalue stream extraction operator exists in the standard library. I think it's because someone realized that there's no good reason for is >> x not to work if is happens to be an rvalue expression of stream type. But many of the existing operator>>s were free functions taking an lvalue reference to basic_istream as their first argument. So adding this rvalue operator>> overload, which delegates to an lvalue one, was the solution to this problem. According to this point of view, the fact that your code compiles is not a bug: it's intentional that you can write an operator>> that takes a non-const lvalue reference to stream type and have it work on rvalues too.
69,321,843
69,323,061
Wrong overload selected when implicity converting to a const type
Consider the code below: #include <iostream> // General overload using a template template <typename SomeType> void some_func(const SomeType p) { std::cout << "Using the general function" << std::endl; } // Specific overload, accepting a 'const double*' type void some_func(const double* p) { std::cout << "Using the function accepting a const double*" << std::endl; } int main() { // This one uses the specific overload, as expected const double *a = new double(1.1); some_func(a); delete a; // This one uses the general function rather than the second overload double *b = new double(1.1); some_func(b); delete b; return 0; } In this piece of code, there are two overloads of the some_func function. The first one is the most general overload, using a template to capture practically any type. The second overload is a specific overload, accepting a const double* type as its argument. In the main function, I first create the variable a of type const double*. When supplying a to some_func, the second overload is selected. This is as expected. Secondly, I create a variable b of type double* (so no const). When supplying the variable b to some_func, it selects the first overload. I would've expected it to select the second overload, as (I think) it should be able to implicitly convert a type double* to const double*. Why does it select the first overload rather than the second overload in this case? For completeness, this is the output of the program: $ g++ main.cpp $ ./a.out Using the function accepting a const double* Using the general function
During template instantiation, this const SomeType p would turn into double* const p which is a better match than const double*. That is, the template's parameter would become a const-pointer to mutable data. In the template function, you can actually modify the data through that pointer, so it can be assumed it is a better match. If you change const SomeType p to const SomeType* p, the specific overload will be selected.
69,322,094
69,322,144
operator[] caller's site source location current workaround
sadly, the current source location can't be used directly in the parameter list of operator[], as this operator has to have only one argument. However, is there a workaround so I can get the callers source line? Consider this code for example: #include <iostream> #include <string> #include <source_location> struct Test { std::source_location src_clone(std::source_location a = std::source_location::current()) { return a; } //this doesnt work: //auto operator[](int a, std::source_location src_clone = std::source_location::current()) auto operator[](int a) { return std::source_location::current(); } }; int main() { auto t = Test{}; auto s1 = t.src_clone(); std::cout << s1.line() << ' ' << s1.function_name() << '\n'; // is there a way to make this print "main.cpp:30"? auto s0 = t[5]; std::cout << s0.line() << ' ' << s0.function_name() << '\n'; }
Found a solution: #include <iostream> #include <string> #include <source_location> #include <string_view> #include <concepts> struct string_like { std::string_view strView; std::source_location s; template <typename T> string_like (T strView, std::source_location s = std::source_location::current()) requires std::constructible_from<std::string_view, T> : strView(strView), s(s) {} }; struct Test { auto operator[](string_like s) { return s.s; } }; int main() { auto t = Test {}; auto s0 = t["hello"]; // prints main.cpp:29 as it should std::cout << s0.line() << ' ' << s0.function_name() << '\n'; }
69,322,194
69,322,221
Conditionally enable member function of base class
I have some classes similar to: class A { void func(); }; class B1 : public A { using A::func; }; class B2 : public A { void func(); }; Because class B1 and B2 in my project share most things, I want to make them as a common class that is distinguished by a template parameter: class A { void func(); }; template <bool Use = false> class B : public A { using A::func; // how can I activate this only if Use is true }; How can I activate using A::func; only if Use is true?
You can use a specialization: template<bool Use> class B : public A {}; template<> class B<false> {}; If the rest of the class is common, you can join them: template<bool Use> class C : public B<Use> { int i; };
69,322,437
69,323,026
Getting all Polite numbers below a certain number
I am trying to write a C++ program that displays all polite numbers that are below a certain number. So for example, if someone were to enter 6, then I would want to print out 3,5,6. I would want to print out 3,5,6,7,9 if the number 9 was to be entered. I've already done the two for loops. I just can't figure out how to test it for all consecutive number combinations, to get the polite numbers. #include <iostream> #include <iomanip> #include <cmath> using namespace std; int main() { cout << "Welcome to the polite numbers program." << endl; int upValue; int num1, num2; cout << "What is the upper value? "; //Ask user for upper limit cin >> upValue; //Stores user input into upValue while (upValue < 1) //Validate user input of upper limit { cout << "What is the upper value? (must be an integer > 0) "; cin >> upValue; } for (num1 = 1; num1 <= upValue; num1++) { //Looping from 1 to upper variable for (num2 = num1 + 1; num2 <= upValue; num2++) { //Looping from 2 to upper //Something goes here to get all polite numbers below a certain number. } } return 0; }
You can break this down into two smaller problems. Here's an example of an implementation. There are likely far more efficient ways to do this, but this should give you an idea of what needs to be done. // calculate the sum of all integers between "start" and "end" inclusive. // hint: the sum of integers between 1 and n is "n(n + 1) / 2". int sum_between(int start, int end) { return (end * (end + 1) - start * (start - 1)) / 2; } // determine if a number polite bool number_is_polite(int num) { // a little shortcut, we know any number less than 3 // cannot be polite if (num <= 2) return false; // get the starting point, which must be at least 2 away // from the target number for (int start = 1; start <= num - 2; start++) { // get the ending point, which must be at least 1 away for (int end = start + 1; end <= num - 1; end++) { // return true if the sum of integers between start/end // inclusive is equal to the target number if (sum_between(start, end) == num) return true; } } // we searched all consecutive integer subsets but nothing // seemed to sum to the target number return false; } Now we can complete your code: #include <iostream> #include <iomanip> #include <cmath> // < insert functions from above > using namespace std; int main() { cout << "Welcome to the polite numbers program." << endl; int upValue; cout << "What is the upper value? "; //Ask user for upper limit cin >> upValue; //Stores user input into upValue while (upValue < 1) //Validate user input of upper limit { cout << "What is the upper value? (must be an integer > 0) "; cin >> upValue; } for (int i = 2; i <= upValue; i++) { if (number_is_polite(i)) cout << i << " "; } cout << endl; }
69,322,519
69,322,572
Is taking a substring in python an O(n) operation?
In C++ if I were to remove the first character from a string it would look something like: string s = "myreallylongstring"; s = s.substr(1); and this would be O(1). [correct me if I'm wrong about that] However in Python's "immutable string" world, does this code run in O(n)? s = "myreallylongstring" s = s[1:] Would it be any faster if I used a list of chars instead?
Slicing any built-in type in Python (aside from memoryview) is O(n) in the general case (main exception being a complete slice of immutable instances, which usually returns the original instance without copying it, since it's not needed). A list of characters wouldn't help; removing a character from the beginning of a list is O(n) (it has to copy everything above it down a slot). A collections.deque could conceivably improve the big-O (they can do O(1) pops from either end), but it would also consume substantially more memory, and more fragmented memory, than the string. For all but the largest strings, you're usually okay even with these O(n) inefficiencies, so unless you've actually profiled and found it to be a cause of problems, I'd stick with the slicing and let it be. That said, you're wrong about C++; s = s.substr(1) is no different from Python's s = s[1:]. Both of them end up copying the entire string save the first character, C++ move assigns back to the original string, while Python replaces the original name binding to the old object with the new one (functionally pretty similar operations). s.substr(1) isn't even using std::string's mutability features; s.erase(0, 1) would in fact erase in-place, mutating the original string, but it would still be O(n) because all the other characters would have to be copied down into the space previously consumed by the deleted characters (no std::string implementation that I know of allows for the storage of an offset from the beginning of the string to find the real data, the pointer to the data points to the first allocated byte at all times).
69,322,614
69,327,507
Can you write depth values to a depth buffer in a compute shader? (Vulkan GLSLS)
I have a raytracer that I need to use in combination with traditional triangle projection techniques, I need to make the raytraced image be able to occlude projected triangles. The easiest way would be to write depth values directly to a depth buffer. Apparently imageStore can only work with color images. Is there a mechanism I can use? The only alternative is to store depth in a color image and then make a dummy shader that sets the depth in a fragment shader.
https://vulkan.gpuinfo.org/listoptimaltilingformats.php It would appear that most implementations don't allow using depth images as storage images. I suggest creating an extra image and copying/blitting it to the depth image.
69,322,655
69,322,858
Why "terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::at: __n (which is 0) >= this->size() (which is 0)"?
So, I keep receiving the terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::at: __n (which is 0) >= this->size() (which is 0) message when I try to run my code. What I'm trying to do is to make it so that it outputs the double stored between the first curly brace and the comma in the nm_1 variable. (*sorry if my code is a bit messy, it's late) int main() { std::string funct; std::cout << "-->"; std::cin >> funct; if (funct.find("math") != std::string::npos) { int bracket_pos_1 = funct.find("{"); int bracket_pos_2 = funct.find("}"); int temp = 0; // int temp_2 = 0; std::string nm_1; std::string nm_2; auto split_string = funct.substr(bracket_pos_1 + 1, bracket_pos_2 - bracket_pos_1 - 1); // string ss = split_string; for (int i = 0; i < 2; i) { std::string nm_1; string ss = split_string; if (ss.at(temp) == '0' || ss.at(temp) == '1' || ss.at(temp) == '2' || ss.at(temp) == '3' || ss.at(temp) == '4' || ss.at(temp) == '5' || ss.at(temp) == '6' || ss.at(temp) == '7' || ss.at(temp) == '8' || ss.at(temp) == '9') { nm_1.at(temp) = ss.at(temp); } else if (ss.at(temp) == '.') { nm_1.at(temp) = ss.at(temp); i++; } else if (ss.at(temp) == ',') { i = 2; } temp++; } nm_1.at(temp - 1) = '0'; // std::cout << split_string; cout << endl << endl << nm_1; } }
The first problem is this: std::string nm_1; nm_1.at(temp) = ... You can't overwrite characters that don't exist in the string. You should rather append to the string. The easiest would be using += operator: nm_1 += ... The second problem is with this: std::string nm_1; for (...) { std::string nm_1; nm_1 += ... Any modification you do to nm_1 will happen to that variable inside the loop. The problem is that this variable is destroyed at the end of one iteration and created anew at the beginning of the next iteration, so all your modification done inside the loop are lost. Just remove that variable definition to fix it: std::string nm_1; for (...) { nm_1 += ...
69,322,775
69,322,843
Class instances not retaining data
I'm running into snags where class instances that I'm storing within a management class are not retaining their data. I wrote out the core concepts that I'm wrestling with into an example here: https://onlinegdb.com/KFqNSz2r6 I have an Action class that acts as a container for some arbitrary action. It's primary function is to act as a state machine to facilitate non-blocking code form a microcontroller project: class Action { public: Action(int interval ,funcp_t callback ) : _interval(interval) , _callback(callback) { } bool trigger(int now) { if (now - _lastCheck > _interval) { _lastCheck = now; return true; } cout << "now: " << now; cout << ", last: " << _lastCheck; cout << ", interval: " << _interval; cout << ", diff: " << (now - _lastCheck); cout << endl; return false; } void fire() { cout << "action fired. last check: " << _lastCheck << endl; _callback(); } private: int _interval = 0; int _lastCheck = 0; funcp_t _callback; }; I also have an ActionManager class that acts as a container and orchestrator class for the actions. The tick method is called to advance the state machines for all actions: class ActionManager { public: void addAction(Action action) { _actions.push_back(action); } void tick() { int now = millis(); for(auto action : _actions) { if(action.trigger(now)) { action.fire(); } } } private: vector<Action> _actions; }; In the rest of my setup code I'm setting up the action manager, adding actions, and then starting an infinite loop (to emulate an arduino loop) to advance the ticks of the ActionManager: void sayHi() { cout << "oh hi" << endl; } void sayHey() { cout << "hey there" << endl; } ActionManager manager = ActionManager(); Action hiAction = Action(5000, sayHi); Action heyAction = Action(1000, sayHey); int main() { cout<<"--> Start <--" << endl; manager.addAction(hiAction); manager.addAction(heyAction); while(true){ manager.tick(); cout << endl; } return 0; } The problem I'm running into is that the _lastCheck property of the Action instances is never updated. The console is reading: --> Start <-- now: 65, last: 0, interval: 5000, diff: 65 now: 65, last: 0, interval: 1000, diff: 65 now: 86, last: 0, interval: 5000, diff: 86 now: 86, last: 0, interval: 1000, diff: 86 now: 98, last: 0, interval: 5000, diff: 98 now: 98, last: 0, interval: 1000, diff: 98 now: 107, last: 0, interval: 5000, diff: 107 now: 107, last: 0, interval: 1000, diff: 107 now: 118, last: 0, interval: 5000, diff: 118 now: 118, last: 0, interval: 1000, diff: 118 Note that the last check value being printed out never changes. I'm pretty sure that this issue is happening because when I call addAction, my actions are being passed by value instead of reference so tried storing the actions as a vector of pointers: class ActionManager { public: void addAction(Action *action) { // accept a pointer to an action _actions.push_back(action); } void tick() { int now = millis(); for(auto action : _actions) { if(action->trigger(now)) { action->fire(); } } } private: vector<Action *> _actions; // store a vector of actions }; ... manager.addAction(&hiAction); // add by passing in the address of the action manager.addAction(&heyAction); But I still get nothing stored in the last check. I feel like I'm missing something simple and I've just been working around the problem for too long to see it. Any ideas?
In your original version, the problem is that when you iterate over the actions, you make copies of the actions instead of referencing them. In for (auto action: _actions) the action is copied. Use for (auto&& action: _actions) instead. The version using pointers, doesn't have that problem and once the difference between now and _lastCheck becomes greater than _interval, _lastCheck should be updated.
69,322,948
69,322,973
My division function returns a zero. Should I declare x differently in main?
#include <iostream> using namespace std; int division(int c, int d); int x = 2; int y = 2; int division(int c, int d) { return (c/d); } int main() { cout << "Hello World!\n"; int x = division(x,y); cout << x; return 0; } I expected the code to show 1 after Hello World!, but it prints 0. I removed int from in front of x (in main()) and ran it again and it returned 1. But I also passed x,x to the division function with the int in front of x (in main()) and it returned 1. So I am not sure how the assignment statement is working.
This expression: int x = division(x,y); is equivalent to writing this: // 'x' was defined globally somewhere here before int x; x = division(x, y); This shadows the previous x variable defined globally and defines a local variable x which again is uninitialized so after passing it in the division() function, your code has Undefined Behavior. (When that happens, the output can be anything, it can be 0, it can even be 1 or something else entirely.) What you want to do is to remove the declaration and turn it into an assignment instead: x = division(x,y); Then the above works properly and gives 1.
69,323,135
69,323,250
What actually is done when `string::c_str()` is invoked?
What actually is done when string::c_str() is invoked? string::c_str() will allocate memory, copy the internal data of the string object and append a null-terminated character to the newly allocated memory? or Since string::c_str() must be O(1), so allocating memory and copying the string over is no longer allowed. In practice having the null-terminator there all the time is the only sane implementation. Somebody in the comments of this answer of this question says that C++11 requires that std::string allocate an extra char for a trailing '\0'. So it seems the second option is possible. And another person says that std::string operations - e.g. iteration, concatenation and element mutation - don't need the zero terminator. Unless you pass the string to a function expecting a zero terminated string, it can be omitted. And more voice from an expert: Why is it common for implementers to make .data() and .c_str() do the same thing? Because it is more efficient to do so. The only way to make .data() return something that is not null terminated, would be to have .c_str() or .data() copy their internal buffer, or to just use 2 buffers. Having a single null terminated buffer always means that you can always use just one internal buffer when implementing std::string. So I am really confused now, what actually is done when string::c_str() is invoked? Update: If c_str() is implemented as simply returning the pointer it's already allocated and managed. A. Since c_str() must be null-terminated, the internal buffer needs to be always be null-terminated, even if for an empty std::string, e.g: std::string demo_str;, there should be a \0 in the internal memory of demo_str. Am I right? B.What would happen when std::string::substr() is invoked? Automactically append a \0 to sub-string?
Since C++11, std::string::c_str() and std::string::data() are both required to return a pointer to the string's internal buffer. And since c_str() (but not data()) must be null-terminated, that effectively requires the internal buffer to always be null-terminated, though the null terminator is not counted by size()/length(), or returned by std::string iterators, etc. Prior to C++11, the behavior of c_str() was technically implementation-specific, but most implementations I've ever seen worked this way, as it is the simplest and sanest way to implement it. C++11 just standardized the behavior that was already in wide use. UPDATE Since C++11, the buffer is always null-terminated, even for an empty string. However, that does not mean the buffer is required to be dynamically allocated when the string is empty. It could point to an SSO buffer, or even to a single static nul character. There is no guarantee that the pointer returned by c_str()/data() remains pointing at the same memory address as the content of the string changes. std::string::substr() returns a new std::string with its own null-terminated buffer. The string being copied from is unaffected.
69,323,228
69,323,242
My computeAverage function is not returning value c++
The problem I am facing is my computeAverage() function is not calculating the average of marks. // computeAverage receives the array with the test scores, and its size, // as paramaters, computes the average and returns the average value. // Uses the local variable average to store temporary and final values. // Uses a for iteration control structure to add all values in the array, // and store the sum in average. ONLY 1 variable declared in this method. int computeAverage(const int anArray[], const int arraySize) { // declare the local integer variable average and initialize to 0 int average = 0; // create a for iteration control structure to add all values in the array for (int i = 0; i < arraySize; i++) { average += anArray[i]; } // the intermediate results are stored in average average = average / arraySize; // return the average value return average; } I have used this computeAverage(&theScores[arraySize], arraySize) to call the function
I have used this computeAverage(&theScores[arraySize], arraySize) to call the function Because you need to simply invoke it as result = computeAverage(&theScores[0], arraySize); Or more generally: result = computeAverage(theScores, arraySize); As you have it now, you are passing the set of elements past the end of your array, not the actual array start.
69,323,327
69,323,677
Why does the C++ array not work beyond the 4th element?
I am learning C++ and had an assignment that asked to take two numbers and insert them into an array. First number is the base number the second number was the array length. The length of the array would be the number of times the base was multiplied by the exponent. For example, if base was 2 and array length was 4 then in element 0 would be 1, element 2 would be 2, etc. and the output would be 2, 4, 8, 16. This worked, up to putting in any base number and then 5. If the length was 5 or above I would get the first four elements correctly then everything after would be a 0. This is the code I came up with and did not work as expected. #include <iostream> using namespace std; int main() { int power, powarray[power]; double base; while(power >= 0) { cout << "Please enter a base number.\n"; cin >> base; cout << "Please enter your exponent.\n"; cin >> power; if (power <= 0) { cout << "Please enter a nonnzero power\n"; } else if (power > 0) { for(int n = 0; n < power; n++) { //powarray[0] = base; powarray[n] = base * powarray[n-1]; cout << powarray[n] << endl; } } } return 0; }
I would first fix your code indentation to make code blocks more clear: 1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 int power, powarray[power]; 7 double base; 8 9 while(power >= 0) { 10 11 cout << "Please enter a base number.\n"; 12 cin >> base; 13 cout << "Please enter your exponent.\n"; 14 cin >> power; 15 16 if (power <= 0) { 17 cout << "Please enter a nonnzero power\n"; 18 19 } else if (power > 0) { 20 21 for(int n = 0; n < power; n++) { 22 23 //powarray[0] = base; 24 powarray[n] = base * powarray[n-1]; 25 cout << powarray[n] << endl; 26 } 27 } 28 } 29 30 return 0; 31 } Now, here are the main issues: You are trying to use the value of power variable twice (lines 6 and 9) before even initializing it. As others mentioned, in C++ you can't initialize an array with a variable like this. Start simple and use a constant to initialize the array maximum size (for example, 100). Line 9 doesn't make much sense, remove this while loop; At the first iteration of the for loop, n equals 0 so line 24 will attempt to get a negative index from powarray. This is not valid; Code structure is confusing. Let's tidy it up by splitting it into three parts: 1: get input; 2: fill array, calculating members values; 3: print the array. Also, remove commented code. These lead to something like this: #include <iostream> using namespace std; int main() { int power; double base; int powarray[100]; /* Get and validate user input */ cout << "Please enter a base number: "; cin >> base; cout << "Please enter your exponent: "; cin >> power; if (power <= 0 || power > 100) { cout << "Please enter a positive power not exceeding " << 100 << endl; return -1; } /* Fill array */ for (int n = 0; n < power; n++) { if (n > 0) powarray[n] = base * powarray[n - 1]; else powarray[n] = base; } /* Print array */ cout << "Array = "; for (int n = 0; n < power; n++) { cout << powarray[n] << " "; } cout << endl; return 0; } Here is a sample output: $ ./a.out Please enter a base number: 2 Please enter your exponent: 12 Array = 2 4 8 16 32 64 128 256 512 1024 2048 4096
69,323,375
69,323,615
How to make a C++ map with class as value with a constructor
I have a class that has a constructor. I now need to make a map with it as a value how do I do this? Right now without a constructor I do. #include <iostream> #include <map> using namespace std; class testclass { public: int x = 1; }; int main() { map<int,testclass> thismap; testclass &x = thismap[2]; } If I added a constructor with arguments how would I add them to the map? I basically need to do #include <iostream> #include <map> using namespace std; class testclass { public: int x = 1; testclass(int arg) { x = arg; } }; int main() { map<int,testclass> thismap; testclass &x = thismap[2]; } This obviously wouldn't work since it requires an argument but I can't figure a way of doing this.
This is how you can add items of your own class to your map. Note : I used a string in testclass to better show difference between key and value/class. #include <iostream> #include <string> #include <map> class testclass { public: explicit testclass(const std::string& name) : m_name{ name } { }; const std::string& name() const { return m_name; } private: std::string m_name; }; int main() { std::map<int, testclass> mymap; // emplace will call constructor of testclass with "one", and "two" // and efficiently place the newly constructed object in the map mymap.emplace(1, "one"); mymap.emplace(2, "two"); std::cout << mymap.at(1).name() << std::endl; std::cout << mymap.at(2).name() << std::endl; }
69,323,387
69,323,425
Printing each character of char array instead of each partial one
Recently I found an interesting question in my exam: what would be printed by the following code. I wondered why this code didn't print sequentially each character of the char array (i.e "dcba") but each partial one (i.e "dcdbcdabcd"), in the reverse order. By the way, I also want to know which topic is related to this problem. Thank you! #include <iostream> #include <string.h> int main() { char mess[] = "abcd"; char* ptr; ptr = mess + strlen(mess); while (ptr > mess) printf("%s", --ptr); return 0; }
char mess[] = "abcd"; means mess aka &mess[0] is the address of the string {'a', 'b', 'c', 'd', \0 }. ptr = mess + strlen(mess); means ptr initially points to the \0 of mess. In the loop ptr is decremented, and the subsequent printf() will print from where ptr points to till it sees \0 (i.e. tail of mess): // initial: abcd\0 ^----- mess aka &mess[0] ^ ptr = mess + strlen(mess) = mess + 4
69,324,126
69,350,133
Resizing window cause my 2D Lighting to stretch
I am trying to implement a simple artificial 2D lighting. I am not using an algorithm like Phong's. However, I am having some difficulty in ensuring that my lighting do not stretch/squeeze whenever the window resize. Any tips and suggestions will be appreciated. I have tried converting my radius into a vec2 so that I can scale them accordingly based on the aspect ratio, however it doesnt work properly. Also, I am aware that my code is not the most efficient, any feedback is also appreciated as I am still learning! :D I have an orthographic projection matrix transforming the light position so that it will be at the correct spot in the viewport, this fixed the position but not the radius (as I am calculating per fragment). How would I go about transforming the radius based on the aspect ratio? void LightSystem::Update(const OrthographicCamera& camera) { std::vector<LightComponent> lights; for (auto& entity : m_Entities) { auto& light = g_ECSManager.GetComponent<LightComponent>(entity); auto& trans = g_ECSManager.GetComponent<TransformComponent>(entity); if (light.lightEnabled) { light.pos = trans.Position; glm::mat4 viewProjMat = camera.GetViewProjectionMatrix(); light.pos = viewProjMat * glm::vec4(light.pos, 1.f); // Need to store all the light atrributes in an array lights.emplace_back(light); } // Create a function in Render2D.cpp, pass all the arrays as a uniform variable to the shader, call this function here glm::vec2 res{ camera.GetWidth(), camera.GetHeight() }; Renderer2D::DrawLight(lights, camera, res); } } Here is my shader: #type fragment #version 330 core layout (location = 0) out vec4 color; #define MAX_LIGHTS 10 uniform struct Light { vec4 colour; vec3 position; float radius; float intensity; } allLights[MAX_LIGHTS]; in vec4 v_Color; in vec2 v_TexCoord; in float v_TexIndex; in float v_TilingFactor; in vec4 fragmentPosition; uniform sampler2D u_Textures[32]; uniform vec4 u_ambientColour; uniform int numLights; uniform vec2 resolution; vec4 calculateLight(Light light) { float lightDistance = length(distance(fragmentPosition.xy, light.position.xy)); //float ar = resolution.x / resolution.y; if (lightDistance >= light.radius) { return vec4(0, 0, 0, 1); //outside of radius make it black } return light.intensity * (1 - lightDistance / light.radius) * light.colour; } void main() { vec4 texColor = v_Color; vec4 netLightColour = vec4(0, 0, 0, 1); if (numLights == 0) color = texColor; else { for(int i = 0; i < numLights; ++i) //Loop through lights netLightColour += calculateLight(allLights[i]) + u_ambientColour; color = texColor * netLightColour; } }
I'm going to compile all the answers for my question, as I had done a bad job in asking and everything turned out to be a mess. As the other answers suggest, first I had to use an orthographic projection matrix to ensure that the light source position was displayed at the correct position in the viewport. Next, from the way I did my lighting, the projection matrix earlier would not fix the stretch effect as my light wasn't an actual circle object made with actual vertices. I had to turn radius into a vec2 type, representing the radius vectors along x and y axis. This is so that I can then modify the vectors based on the aspect ratio: if (aspectRatio > 1.0) light.radius.x /= aspectRatio; else light.radius.x /= aspectRatio; I had posted another question here, to modify my lighting algorithm to support an ellipse shape. This allowed me to then perform the scalings needed to counter the stretching along x/y axis whenever my aspect ratio changed. Thank you all for the answers.
69,324,677
69,324,918
GCC, GTK on Windows10 ld.exe: cannot find -ldwmapi
I'm pretty new to all this so excuse me if I put useless info, or forget useful ones on this post. I'm trying to code a GUI with GTK in C on Windows10. So I have installed Msys2 in order to use GTK. In Msys2 I have installed the basic pkgs and all the GTK pkgs. Then on VScode I have installed an extension to link external libraries { "configurations": [ { "name": "Win32", "includePath": [ "${workspaceFolder}/**", "C:\\msys64\\mingw32\\include\\gtk-3.0\\", "C:\\msys64\\mingw32\\include\\glib-2.0", "C:\\msys64\\mingw32\\include\\pango-1.0", "C:\\msys64\\mingw32\\include\\harfbuzz", "C:\\msys64\\mingw32\\include\\cairo", "C:\\msys64\\mingw32\\include\\gdk-pixbuf-2.0", "C:\\msys64\\mingw32\\include\\atk-1.0" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "windowsSdkVersion": "10.0.19041.0", "compilerPath": "D:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.29.30133\\bin\\Hostx64\\x64\\cl.exe", "cStandard": "c17", "cppStandard": "c++17", "intelliSenseMode": "windows-msvc-x64" } ], "version": 4 } Here's what it looks like, but I believe this doesn't really matter as I manually compile on the powershell. Here's how I compile my file (in a .bat file): gcc main.c -o mikey.exe -LC:\msys64\mingw32\lib\gtk-3.0 -Wl,-luuid -LC:\msys64\mingw32\lib -lgtk-3 -lgdk-3 -lz -lgdi32 -limm32 -lshell32 -lole32 -ldwmapi -lwinmm -lsetupapi -lcfgmgr32 -latk-1.0 -lgio-2.0 -lpangowin32-1.0 -lpangocairo-1.0 -lgdk_pixbuf-2.0 -lcairo-gobject -lpango-1.0 -lharfbuzz -lcairo -lgobject-2.0 -lglib-2.0 -lintl -IC:\msys64\mingw32\include\gtk-3.0 -IC:\\msys64\\mingw32\\include\\glib-2.0 -IC:\\msys64\\mingw32\\include\\pango-1.0 -IC:\\msys64\\mingw32\\include\\harfbuzz -IC:\\msys64\\mingw32\\include\\cairo -IC:\\msys64\\mingw32\\include\\gdk-pixbuf-2.0 -IC:\\msys64\\mingw32\\include\\atk-1.0 All the -l args come from: C:\msys64\mingw32\bin\pkg-config.exe --libs gtk+-3.0 This looks bad because I failed at trying to put pkg-config on PATH or wtv x) And the -I were consecutively asked by the compiler. Sooooo now I get the following error when compiling: c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../../mingw32/bin/ld.exe: cannot find -ldwmapi collect2.exe: error: ld returned 1 exit status I know that the dwmapi.dll exists in my System32 folder, but I don't even know if it the subject here. I am completly lost tbh My main.c if necessary: #include <gtk/gtk.h> int main(int argc, char *argv[]) { GtkWidget *window; gtk_init(&argc, &argv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL); gtk_widget_show(window); gtk_main(); return 0; }
Different MinGW versions usually don't play well together. Since MSYS2 ships it's own MinGW, you should uninstall the other version you have in C:\mingw, or at least remove it from PATH.
69,324,768
69,324,978
C ++: library for conversion, Ex: binary -> decimal | binary -> hexadecimal etc
for my project i need to convert some numbers, exemple: Binary --> decimal Decimal--> binary Binary --> hexadecimal Hexadecimal --> binary Etc... I tried to create some functios, but it's long operation and i immediately need a converter. Someone know a library for do this, then, where do i find it.
Example some steps involving strings and numbers #include <iostream> #include <bitset> #include <cassert> #include <string> #include <sstream> int main() { auto binary = std::stoi("0110", nullptr, 2); auto hex = std::stoi("f", nullptr, 16); assert(binary == 6); assert(hex == 15); std::stringstream os; os << std::hex << hex; // todo add formatters. std::cout << os.str() << std::endl; std::bitset<4> bits{ binary }; std::cout << bits.to_string() << std::endl; return 0; }
69,324,896
69,324,936
I convert Int to Float but the Id-Type doesn't change
I convert int to float and input 1.23 to 'a' but output is 1 what is wrong? int a = 123; static_cast<float>(a); cout << typeid(a).name(); //int cin >> a; //1.23 cout << a; //1 return 0;
You have to asign the return value to a variable of the preferred type: float result = static_cast<float>(your_var);
69,324,980
69,325,109
Is shared_ptr<void>::reset() lock-free?
Imagine the following: // SECTION A MyClass* object = new MyClass(); std::shared_ptr<void> sharedObject; // SECTION B (sharedObject is empty) sharedObject.reset(object); Is section B lock-free for an empty sharedObject? Or does it depend of the implementation?
This depends on implementation. Some pointers: Overhead and implementation of using shared_ptr Linking pthread disables lock-free shared_ptr implementation
69,325,050
69,325,321
Customized widget in scroll area cannot be scrolled up or down after setting setWidgetResizable to true in qt
I have a problem when working with QScrollArea. Mainly, I want to add a customized widget into a scroll area to reach: scroll widget if widget's size is larger than parent(scroll) customized widget can automatically resize its size to fill all space of scroll if it is smaller than scroll But I failed. Setting setWidgetResizable to true can resize widget but cannot scroll. Otherwise, can scroll widget not resize. I'm using qt-5.15.x. Here is the minimal example, I can scroll it if I comment out line scroll->setWidgetResizable(true);: customwidget.h #ifndef CUSTOMWIDGET_H #define CUSTOMWIDGET_H #include <QWidget> #include <QSize> #include <QResizeEvent> class CustomWidget : public QWidget { Q_OBJECT public: explicit CustomWidget(QWidget *parent = nullptr); ~CustomWidget()=default; protected: void paintEvent(QPaintEvent *e); void resizeEvent(QResizeEvent *e); QSize sizeHint() const override; private: QVector<QRectF> _rects; QSize _size; }; #endif // CUSTOMWIDGET_H customwidget.cpp #include "customwidget.h" #include <QPainter> CustomWidget::CustomWidget(QWidget *parent) : QWidget(parent) { _size = QSize(120, 200); for(int i = 0; i < 10; i++) { QRectF rect(QPointF(10, 60*i+2),QSize(100, 50)); _rects.push_back(rect); } } void CustomWidget::paintEvent(QPaintEvent *e) { QPainter painter(this); // background painter.setBrush(QColor(130,130,130)); painter.drawRect(QRectF(QPointF(0,0), _size)); // items for(int i = 0; i < 10; i++) { painter.setBrush(QColor(43,43,43)); painter.drawRect(_rects[i]); painter.setPen(QColor(255,255,255)); painter.drawText(_rects[i], QString("ITEM %1").arg(QString::number(i))); } } void CustomWidget::resizeEvent(QResizeEvent *e) { _size = e->size(); } QSize CustomWidget::sizeHint() const { int rows = _rects.size(); int height = rows * 60+2; height = std::max(height, parentWidget()->height()); int width = 120; return QSize(width, height); } Add the mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H mainwindow.cpp #include "mainwindow.h" #include "./ui_mainwindow.h" #include <QScrollArea> #include "customwidget.h" #include <QVBoxLayout> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); setGeometry(0,0,300,200); QVBoxLayout *layout = new QVBoxLayout(centralWidget()); layout->setContentsMargins(0,0,0,0); CustomWidget *cw = new CustomWidget(); QScrollArea *scroll = new QScrollArea(this); scroll->setWidgetResizable(true); scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scroll->setStyleSheet("QScrollArea{background:rgb(0,0,0);border:none;}"); scroll->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); scroll->setWidget(cw); layout->addWidget(scroll); } MainWindow::~MainWindow() { delete ui; }
A possible solution is to set the sizePolicy to Minimum: CustomWidget::CustomWidget(QWidget *parent) : QWidget(parent) { _size = QSize(120, 200); for(int i = 0; i < 10; i++) { QRectF rect(QPointF(10, 60*i+2),QSize(100, 50)); _rects.push_back(rect); } setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); }
69,325,234
69,325,314
My implementation of mathematical formula returns different value than calculator
using namespace std; #include <iostream> #define _USE_MATH_DEF #include <conio.h> #include <cmath> int main() { const double e = 2.71; double x, a, b, c, A, B, C, M; cout << "Enter the value of x, a, b and c: "; cin >> x >> a >> b >> c; A = x + pow(sqrt(x + a), 3); // cout << A; B = x - sqrt((abs(x - b))); // cout << B; C = A / B; M = pow(e, -1 * c) * C; cout << "The result of function is " << M; _getch(); return 0; } For example, lets define x=1, a=4, b=5, c=1. Calculator returns M as -0.9547605358, but code calculates M as -4.49459. This is mathematical formula that I need to code:
Here I see some problems, namely A must be A = x + pow(sqrt(x + a), 1.0/3.0); B and C definition is correct, but M must be M = pow(e, -1 * c * x) * C; I would also like to point out that conio.h is a non standard header file and _getch() is non standard.
69,325,382
69,325,449
How do i switch console output to horizontal perspective? Chessboard problem
I got asked by my teacher to do a chessboard, this is what it looks like when I build it , my problem is that my teacher wants it horizontally like A8, B8, C8, and when I build it it's A8, A7, A6, so I kinda need to swap it but I don't know-how. #include <iostream> using namespace std; int main() { for(char i = 65; i < 73; i++) { cout << "\n"; cout << i << "8" << " "; cout << i << "7" << " "; cout << i << "6" << " "; cout << i << "5" << " "; cout << i << "4" << " "; cout << i << "3" << " "; cout << i << "2" << " "; cout << i << "1" << " "; cout << "\n"; } }
You have to print letters from A to H on each line. Also, printing numbers is much easier with a loop too. for(int i = 8; i >= 1; i--) { for(char c = 'A'; c <= 'H'; c++) { std::cout << c << i << " "; } std::cout << '\n'; }
69,325,414
69,325,717
Substitute all chess pieces in a .o file makefile
I have a makefile about a chess project. The current make Chess rule looks like this Chess: main.o board.o player.o chess.o square.o piece.o position.o pawn.o rook.o king.o queen.o bishop.o knight.o $(CC) main.o board.o player.o chess.o square.o piece.o position.o pawn.o rook.o king.o queen.o bishop.o knight.o $(OUTPUT) and I want to replace it with something like this Chess: main.o board.o player.o chess.o square.o piece.o position.o chesspieces.o $(CC) main.o board.o player.o chess.o square.o piece.o position.o chesspieces.o $(OUTPUT) What I tried : chesspieces.o: ./src/pieces/king.cc ./src/pieces/knight.cc ./src/pieces/bishop.cc ./src/pieces/queen.cc ./src/pieces/pawn.cc ./src/pieces/rook.cc ./src/pieces/piece.cc $(CC) $(INCLUDES) ./src/pieces/king.cc ./src/pieces/knight.cc ./src/pieces/bishop.cc ./src/pieces/queen.cc ./src/pieces/pawn.cc ./src/pieces/rook.cc ./src/pieces/piece.cc Gives me a bunch of undefined references to Position, Square, Board. Piece is the abstract class which every chess piece inherits from and it includes a Color and a Position class, but I already added rules for those in the Chess rule. Should I add them again? Also an extra question: I want to store my object files in a separate folder, will this cause any issues?
I'm not sure if its even possible to combine many source files into a single object without using weird hacks. .o files are separate compilation units and its the linkers job to merge them to create binaries (e.g. libraries). Your getting undefined references because what your actually doing for chesspieces.o is generating an executable called a.out (if your using gcc). Use -c to generate object files (one per input .cc file). You might want to reorganize your make targets instead, usually you'd have one target per produced binary. e.g. if your making a static library called foo: # Rules for pieces/king.o, etc foo.a: pieces/king.o pieces/knight.o pieces/bishop.o # ... # Combine the object files ar rcs $@ $^ So to combine your chesspieces: chesspieces.a: # pieces/king.o ... ar rcs $@ $^ Chess: ... chesspieces.a $(CXX) ... -lchesspieces -L<dir where chesspieces.a is stored> # Links your chesspiece lib to your Chess executable Note that on Linux static libs are basically just archives of object files so we use ar with rcs to generate a static library. I've used "magic" make variables $@ (the target name) and $^ (the target dependencies). Also we have to pass -lchesspieces and -L<dir> to the final compilation of Chess so the linker can find all the symbols defined in the .o files that are part of chesspieces.a Generally during the build a .o file is generated for every source (.cc) file as an intermediate step between compiling and linking Note: You tagged your question "cpp" so I changed CC to CXX, CC is the C compiler CXX is the c++ compiler
69,325,425
69,325,465
Access violation in custom comparator in priority queue
I have an issue were a program of mine throws an access violation. Through debugging I found that for some reason the comparator-function is null. However I am not sure on why that is or how to fix it. I created a minimum working example to reproduce the issue: #include "Tryout.h" #include <queue> struct Event { uint64_t mv_timeout; }; bool CompareEvents(const Event& a, const Event& b) { return a.mv_timeout < b.mv_timeout; } int main() { std::priority_queue<Event, std::vector<Event>, decltype(&CompareEvents)> mt_eventQueue; Event lo_event1{ .mv_timeout = 1, }; Event lo_event2{ .mv_timeout = 2, }; mt_eventQueue.push(lo_event1); mt_eventQueue.push(lo_event2); return 0; } When executing it crashes when adding the second event. Exception thrown at 0x0000000000000000 in Tryout.exe: 0xC0000005: Access violation executing location 0x0000000000000000. As mentioned it seems the comparing function is null, even tough I passed it via template. What is going wrong here?
You need to specify the comparison function explicitly in the constructor std::priority_queue<Event, std::vector<Event>, decltype(&CompareEvents)> mt_eventQueue( CompareEvents ); Otherwise the default argument will be used for the comparison function that will yield a null pointer. The used constructor has the following declaration with default arguments explicit priority_queue(const Compare& x = Compare(), Container&& = Container());
69,325,512
69,325,863
Is "overcrowding" a member initializer list a thing?
Let's say I have a class which has many members that do have a default constructor defined, so it's not required to initialize them in initializer list (like in the example below). Is there a point, where initializing list gets "overcrowded" so much so that it's kinda awkward to read and it's better to assign things in a constructor's body for the sake of readability? class Foo { public: Foo(const std::vector<Thing>& things) : m_Vec1(1.0f, 1.0f, 1.0f), m_Vec2(1.0f, 1.0f, 1.0f), m_Vec3(1.0f, 1.0f, 1.0f), m_Vec4(1.0f, 1.0f, 1.0f), m_SomeFile("some/path/to/file.txt"), m_Model("some/path/to/model.obj"), m_AnotherVec(1.0f, 1.0f, 1.0f), m_Things(things), m_Size(things.size()) {} private: vec3f m_Vec1; vec3f m_Vec2; vec3f m_Vec3; vec3f m_Vec4; FileClass m_SomeFile; Model m_Model; vec3f m_AnotherVec; std::vector<Thing> m_Things; uint32_t m_Size; };
You can use whitespace to make "overcrowded" code more readable. Example: Foo(const std::vector<Thing>& things) : m_Vec1(1.0f, 1.0f, 1.0f), m_Vec2(1.0f, 1.0f, 1.0f), m_Vec3(1.0f, 1.0f, 1.0f), m_Vec4(1.0f, 1.0f, 1.0f), m_SomeFile("some/path/to/file.txt"), m_Model("some/path/to/model.obj"), m_AnotherVec(1.0f, 1.0f, 1.0f), m_Things(things) {} I don't think the readability could be improved by using the constructor body to assign the members after initialisation. The example can be further simplified by using constants for repeated initalisers, and default member initialisers instead of the member init list: class Foo { public: Foo(const std::vector<Thing>& things) : m_Things(things) {} private: constexpr inline static vec3f default_vec{1.0f, 1.0f, 1.0f}; vec3f m_Vec1 {default_vec}; vec3f m_Vec2 {default_vec}; vec3f m_Vec3 {default_vec}; vec3f m_Vec4 {default_vec}; FileClass m_SomeFile {"some/path/to/file.txt"}; Model m_Model {"some/path/to/model.obj"}; vec3f m_AnotherVec {default_vec}; std::vector<Thing> m_Things; }; Note that I've removed the m_Size member. It's entirely redundant since the size of the vector is stored within the vector.
69,326,062
69,326,336
Template explicit specialization in class using inheritance
Yesterday I asked about template explicit specialization in class. Link. Now I have the same purpose but now I wanna use inheritance to avoid code duplication. If I declare a function in the base class I cannot declare specialization of this function in the derived class. My code: #include <stdexcept> #include <iostream> class Base { public: template <typename T> T fun() { throw std::runtime_error("Unsupported template param"); } }; class Derived : public Base { }; template <> bool Base::fun<bool>() { return true; } template <> float Derived::fun<float>() { return 5.6f; } template <> double Derived::fun<double>() { return 5.684; } int main() { Derived d; bool d_b = d.fun<bool>(); float d_f = d.fun<float>(); double d_d = d.fun<double>(); char d_error = d.fun<char>(); } VS code errors: use of inherited members is not allowed g++ error: template id "fun" for "float Derived :: fun ()" does not match any template declaration Intel C++ compiler: source/app.cpp:25:16: error: no function template matches function template specialization 'fun' float Derived::fun<float>() ^ source/app.cpp:30:1: error: extraneous 'template<>' in declaration of variable 'fun' template <> ^~~~~~~~~~~ source/app.cpp:31:17: error: redefinition of 'fun' as different kind of symbol double Derived::fun<double>() ^ source/app.cpp:25:16: note: previous definition is here float Derived::fun<float>() If it is impossible in C++, please answer another question: what is a wide-known practice in c++ to do what I want. Before I used D language and one man says me I don't ask a question "Why" to myself. And instead, I just try to transfer D methods to C++. I agree. That's why I ask. Maybe a better way is to ignore templates and declare separated functions? For example: funToBool() funToFloat() funToDouble()
This will compile if you add a public template definition of fun in Derived. But that will probably not do what you want. In particular d.fun<bool>(); will not execute the implementation in Base, but the implementation in Derived. You cannot specialize template functions in derived classes. You also cannot use subtype polymorphism on template functions: template cannot be virtual. You can achieve some type of static polymorphism using CRTP. Yes removing templates and working with separated functions would work (a.toX()...). Another option is to work with overloads (i.e. passing a dummy argument or the destination variable and write different implementations). Adding an example for the dummy argument solution as requested: namespace TO { static const bool BOOL = false; static const double DOUBLE = 0.0; static const int INT = 0; } struct A { bool convert(bool dummy) { return true; } }; struct B : public A { using A::convert; // important int convert(int dummy) { return 2; } double convert(double dummy) { return 3.0; } }; int main() { B b; std::cout << b.convert(TO::BOOL) << std::endl; std::cout << b.convert(TO::DOUBLE) << std::endl; std::cout << b.convert(TO::INT) << std::endl; } With this kind of solution there is a risk of implicit conversion when calling the function. toX() might be a safer option.
69,326,243
69,357,867
What is the correlation between RadioMedium's maxCommunicationRange parameter and Radio transmitter's power parameter?
Warm greetings to all I want to have an understanding of the RadioMedium's parameter: maxCommunicationRange and the Radio transmitter's parameter : power Indeed, I wanted my nodes don't communicate with neighbors if those later are beyond a threshold range. I parameterized as follow : *.radioMedium.*.power = -110dBm *.radioMedium.*.bandwidth = 2.8MHz *.radioMedium.*.centerFrequency = 2.4GHz *.radioMedium.*.maxTransmissionPower = 2.24mW *.radioMedium.*.maxTransmissionDuration = 1000ms *.radioMedium.*.maxCommunicationRange = 20m **.radio.transmitter.power = 2.24mW But I'm surprised to see that packets are still transmitted to all the nodes in my network. I even set *.radioMedium.*.maxCommunicationRange = 0m but all the nodes still receive packets. Unlikely, when I variate the transmitter's power parameter (**.radio.transmitter.power = 0.05mW), I clearly saw that only the nodes which are at a certain distance around the sender node are receiving the packets. But the problem is that I can't exactly know this admissible distance of communication whereas I need to know it in my work. 1- How does this parameter ( maxCommunicationRange ) work? 2- How can I impose to my nodes not to communicate with each other beyond a certain distance? 3- What is the relationship between maxCommunicationRange and **.radio.transmitter.power? I'm using omnetpp-6.0pre11 and INET 4.3 Many thanks for your continued support on Stackoverflow.
The maxCommunicationRange is the parameter of the MediumLimitCache submodule of RadioMedium. The medium limit cache is an optimization, so that the radio medium doesn't have to calculate the ranges with each transmitter/receiver pair from the power and sensitivity, but you can specify some values to use (by default the medium limit cache is not used.) These ranges (max communication and interference range) are used for further optimization, such as the range filter (rangeFilter parameter in the radio medium). The filter can be set so that transmissions which are beyond the max communication range are not sent to the nodes. In your example, if you want the radio medium to not send any transmissions to nodes beyond the max communication range, you also need to set the range filter to communication range (see the radio medium NED documentation). So by default, the max communication range of the medium limit cache is not used, but the success of a transmission is calculated from the transmitter power, attentuation due to distance and the receiver sensitivity. To set a communication range, the power and sensitivity need to be fine-tuned. However, you mentioned that it is important for the communication range to be a specific distance. For this, the UnitDiskRadio model might be better suited (if you don't care about other things about the transmissions such as signal attenuation). In this model, you can set specific communication ranges for each transmitter, and transmissions in the range are always successful, out of range they are never.
69,326,545
69,326,708
connect dynamically created buttons in qt5
I have a scenario where I am asking the user for a number between 1 and 10 and creating that number of buttons of the type QPushButton. I then want to create a function such that when I click the button the number on the button gets printed.
Just use a lambda function like this: for (int i = 1; i < numButtons; i++) { QPushButton *btn = new QPushButton(...); connect(btn, &QPushButton::clicked, [=]() { // Do something with 'i' } }
69,326,660
69,326,874
How to make a function call via pointer-to-member-function to a templated function?
I tried to compile the following code. #include <iostream> class Base { public: template <typename T> T fun() { std::cout<<"CALLED!"<<std::endl; return T(); } }; class Derived : public Base { }; template<class T> T (Derived::*func_ptr)() = &Base::fun; int main() { Derived d; ///how to call? } To my surprise, this compiled in both clang and gcc. This gives me the idea that somehow we should be able to call fun by func_ptr. However, I cannot think of what the syntax should be to call the function by this pointer. What is the syntax for it and how is it explained? Also another thing is, I cannot think of a reason for this to compile. Where is this behavior defined in C++ standard?
However, I cannot think of what the syntax should be to call the function by this pointer. What is the syntax for it? (d.*func_ptr<int>)(); // or other template argument How is it explained? Where is this behavior defined in C++ standard? func_ptr is a variable template. There are very few rules in the Standard specifically about variable templates, but they are allowed in C++17 and later by [temp.pre] paragraphs 1 and 2. In your definition template<class T> T (Derived::*func_ptr)() = &Base::fun; the expression &Base::fun is a pointer to overloaded function, as described in [over.over]. When each specialization of the func_ptr template is instantiated, it has a specific pointer-to-function type T (*)() as the target, and the correct template argument for Base::fun<T> can be deduced from that. To use a variable template, template arguments must be provided. (Template argument deduction can only happen for function templates and class templates.) So func_ptr<int> is an expression of type int (*)(). Then that's combined with the syntax (obj.*mem)(args) for calling a pointer to member function.
69,327,002
69,346,099
Arduino HTTP.post() returns -11
I cannot not find a solution for this problem. Everything worked very well when I tried a month ago, but now, when I launch it, it does not work anymore. The problem occurs when I send http.POST(data); request to the given address, but Serial.println(httpResponseCode); returns -11. I've tested my domain URL on Postman and everything worked there. Thank you for any help. #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <WiFiClient.h> #include <DallasTemperature.h> #include <OneWire.h> #include <ArduinoJson.h> #define ONE_WIRE_BUS 4 // D2 pin of NodeMCU OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); // Time configuration unsigned long lastTime = -300000; unsigned long timerDelay = 300000; unsigned long errorThreshold = 5000; // WiFi configuration const char *ssid = "myssid"; const char *wifiPassword = "mypass"; // Authentication configuration const char *username = "myusername"; const char *password = "mypassword"; // Domain name with URL path or IP address with path const char *authentication = "myurl"; // Functions int authenticate(); // HTTP WiFiClient client; HTTPClient http; String token = ""; void setup() { // Sets the data rate in bits per second for serial data transmission Serial.begin(9600); WiFi.begin(ssid, wifiPassword); Serial.println("Connecting to WiFi..."); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); sensors.begin(); Serial.print("Connected to WiFi with IP Address: "); Serial.print(WiFi.localIP()); Serial.print("\n\n"); while (authenticate() != 200) { } } void loop() { if ((millis() - lastTime) > timerDelay) { if (WiFi.status() == WL_CONNECTED) { // ... } else { Serial.println("WiFi Disconnected"); digitalWrite(2, LOW); delay(2000); digitalWrite(2, HIGH); lastTime = millis() - timerDelay + errorThreshold; } } } int authenticate() { // Add headers to Authorization request http.begin(client, authentication); http.addHeader("Content-Type", "application/json"); String data = "{\"username\":\"" + String(username) + "\"," + "\"password\":\"" + String(password) + "\"}"; // Send Authorization request int httpResponseCode = http.POST(data); token = http.getString(); Serial.println(httpResponseCode); return httpResponseCode; } I use Visual Code as a code editor. My platformio.ini: lib_deps = milesburton/DallasTemperature @ ^3.9.1 bblanchon/ArduinoJson @ ^6.18.4
http.begin(client, authentication); Please make sure the authentication URL is HTTP and not HTTPS.
69,327,086
69,327,189
Global Array of Functions pointers
How to make a global array of functions in C++? I want this: //f.cpp #include "head.h" void f() {}; //g.cpp #include "head.h" void g() {}; //head.h #pragma once void f(); void g(); typedef void (*f_t)(); f_t Fs[2] = {f,g}; //main.cpp #include "head.h" int main() { Fs[0](); } Something like this worked for me in C, but I'm new to C++. I tried a lot of way's of compiling stuff but, each time, g++ gave me "multiple definitions" errors. How to create global arrays without initialising it through a function? I tried to implement the same but with the array in a separate "const_array.h" file; that solves the problem but, when I include it to other files, it gives me anyway the same error.
Add one more file: //head.h #pragma once void f(); void g(); typedef void (*f_t)(); extern f_t Fs[2]; //head.cpp #include "head.h" f_t Fs[2] = {f,g};
69,327,246
69,327,378
Converting HEXA 64 bits numbers to int
I'm making a college job, a conversion between hexa numbers enclosed in a stringstream. I have a big hexa number (a private key), and I need to convert to int, to put in a map<int,int>. So when I run the code, the result of conversion is the same for all the two hexa values inserted, what is incorrect, it should be differente results after conversion. I think it's an int sizes stack problem, because when I insert short hexas, it works greatly. As shown below the hexa has 64 bits. Any idea to get it working? int main() { unsigned int x; std::stringstream ss; ss << std::hex << "0x3B29786B4F7E78255E9F965456A6D989A4EC37BC4477A934C52F39ECFD574444"; ss >> x; std::cout << "Saida" << x << std::endl; // output it as a signed type std::cout << "Result 1: " << static_cast<std::int64_t>(x) << std::endl; ss << std::hex << "0x3C29786A4F7E78255E9A965456A6D989A4EC37BC4477A934C52F39ECFD573344"; ss >> x; std::cout << "Saida 2 " << x << std::endl; // output it as a signed type std::cout << "Result 2: " << static_cast<std::int64_t>(x) << std::endl; }
Firstly, the HEX numbers in your examples do not fit into an unsigned int. You should clear the stream before loading the second HEX number there. ... std::cout << "Result 1: " << static_cast<std::int64_t>(x) << std::endl; ss.clear(); ss << std::hex << "0x3C29786A4F7E78255E9A965456A6D989A4EC37BC4477A934C52F39ECFD573344"; ss >> x; ...
69,327,416
69,359,111
MoveWindow does not scale the window when moving to a different screen
I have a Windows application with floating windows. I am running it on a multi-monitor setup (FHD, 4K). The application is marked as system-aware, so we pick the current DPI value for the primary monitor and scale according to that. After that, the OS bitmap-scales it. The application is running on Windows 10. Now, when one of the floating windows is dragged to another monitor, the OS bitmap-scales it automatically, and it all works fine. The problem is that we have some windows without a title bar, and we have code to move those windows by dragging from the client area of the window. When the mouse is released, we call the MoveWindow() API to move the window to the target location. This works fine on a single monitor, but when we drop the window on a different monitor, it does not bitmap-scale, it seems to lose its drop location. The OS only seems to bitmap-scale when we drag a window by its title bar and not when it is moved programmatically. Any ideas on how this automatic scaling can be achieved when moving a window programmatically?
So it depends on how the window is created. I fixed it by creating the window using WS_CAPTION style and then removing that style later. I am not sure what is does internally but it now scales correctly when it is moved to another screen either through mouse-drag or by using an API such as MoveWindow. ::CreateWindowEx(WS_EX_PALETTEWINDOW,...,..., WS_POPUP | WS_CAPTION,...); ::SetWindowLong(hWnd, GWL_STYLE, ::GetWindowLong(hWnd, GWL_STYLE) & ~WS_CAPTION);
69,327,986
69,328,453
Reading array elements from string
I have an array of pairs<string,string> encoded into a database string, I am attempting to access the array element to eventually construct a std::map<std::string,std::string> but attempting to acccess array elements from my string gives me an exception bool test_json_map_string_string() { std::string database_string { "[{\"bootloaderVersion\":\"4\"},{\"date\":\"2021/09/24\"},{\"type\":\"5\"},{\"version\":\"175\"}]"}; // database_string=[{"bootloaderVersion":"4"},{"date":"2021/09/24"},{"type":"5"},{"version":"175"}] std::cout << "database_string=" << database_string << std::endl; using json = nlohmann::json; try { json object_array = json::array(); json json_str( database_string ); json_str.get_to(object_array); // object_array.size=1 object_array.is_array=0 std::cout << "object_array.size=" << object_array.size() << " object_array.is_array=" << object_array.is_array() << std::endl; for( size_t index = 0; index < object_array.size(); ++index ) { // object_array[0] = std::cout << "object_array[" << index << "] = " << object_array[index] << std::endl; } return true; } catch( const std::exception& except ) { // except=[json.exception.type_error.305] cannot use operator[] with a numeric argument with string std::cerr << "except=" << except.what() << std::endl; return false; } } How do I initialize nlohmann::json with a std::string and then access array elements within it? The method I used does not seem to recognize the array. Best regards
get_to() is an assignment, and does not parse. What you want is: json object_array = json::parse(database_string); Example: https://godbolt.org/z/WsrvEc5MK
69,328,493
69,401,578
Why is compile-time execution significantly faster than runtime execution?
Contrary to what this question says, this piece of code is exhibiting some weird behaviour: long long int fibonacci(int num) { if (num <= 2) return 1; return fibonacci(num - 1) + fibonacci(num - 2); } int main() { auto t1 = std::chrono::high_resolution_clock::now(); long long int x = fibonacci(45); auto t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::milli> time(t2 - t1); std::cout << "Time taken: " << time.count() << "ms"; } On my machine, this compiles in ~700ms with -O3 (GCC) and the output is: Time taken: 2667.55ms I rewrote the above code with constexpr as follows: constexpr long long int fibonacci(int num) { if (num <= 2) return 1; return fibonacci(num - 1) + fibonacci(num - 2); } int main() { auto t1 = std::chrono::high_resolution_clock::now(); constexpr long long int x = fibonacci(45); auto t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::milli> time(t2 - t1); std::cout << "Time taken: " << time.count() << "ms"; } Which compiles in roughly the same time but the output is: Time taken: 0ms As it stands, evaluating fibonacci(45) at compile-time is much faster than evaluating it at runtime. To eliminate multi-core compiling as a reason (which definitely isn't), I re-ran the second block above with fibonacci(60). Again, the code compiles in the same amount of time but the output is: Time taken: 29499.6ms What causes this big performance gap?
Basically, for that short piece of code, compile time does not matter. Even, if you do compile time evaluation. The main problem is here the utmost bad algorithm used here. Using 2 recursive calls which will then call again 2 recursive functions and so on and so on has really the worst case time complexity for such a simple algorithm. That problem can and must be solved with an iterative approach. Something like that: unsigned long long fibonacci(size_t index) noexcept { unsigned long long f1{ 0ull }, f2{ 1ull }, f3{}; while (index--) { f3 = f2 + f1; f1 = f2; f2 = f3; } return f2; } If you use this function, then, reagrdless of optimization or not, your main will run in below 1ms. In you original main function, if you do not use the result of the calculation, so the variable "X", then optimizing compiler can eliminate the complete function call. It is not necessary to call that function. The result is not used. Make the following experiment. Add std::cout << x << '\n'; as the last statement in your main function. You will be surprised. With enabled optimization, the function will be called at the very end. And you time measurement measures nothing. Now to the compiler time version. Also the compiler will internally used optimized code. And it will convert the nonesense recursive approach to an iterative approach. And to calculate that values will take less time than the compiler overhead functions. So, that is the real reason. And the Fibonacci numbers can always be compiled fully at compile time. There are only 93 possible results for an 64 bit result value. See the following approach, which creates a compile time array of all Fibonacci numbers. And if you want the n'th number, it is just a lookup value. This will work very fast in either non-optimized or optimized mode. It is the fasted possible solution for that problem. #include <iostream> #include <utility> #include <array> #include <algorithm> #include <iterator> // All done during compile time ------------------------------------------------------------------- constexpr unsigned long long getFibonacciNumber(size_t index) noexcept { unsigned long long f1{ 0ull }, f2{ 1ull }, f3{}; while (index--) { f3 = f2 + f1; f1 = f2; f2 = f3; } return f2; } // Some helper to create a constexpr std::array initilized by a generator function template <typename Generator, size_t ... Indices> constexpr auto generateArrayHelper(Generator generator, std::index_sequence<Indices...>) { return std::array<decltype(std::declval<Generator>()(size_t{})), sizeof...(Indices) > { generator(Indices)... }; } template <size_t Size, typename Generator> constexpr auto generateArray(Generator generator) { return generateArrayHelper(generator, std::make_index_sequence<Size>()); } constexpr size_t MaxIndexFor64BitFibonacci = 93; // This is the definition of a std::array<unsigned long long, 93> with all Fibonacci numbers in it constexpr auto Fib = generateArray<MaxIndexFor64BitFibonacci>(getFibonacciNumber); // End of: All done during compile time ----------------------------------------------------------- // The only code executed during runtime int main() { // Show all Fibonacci numbers up to border value for (const auto fib : Fib) std::cout << fib << '\n'; }
69,328,638
69,328,726
Error "Invalid padding length on received packet" when connecting to winsock server using PuTTY
I'm mostly new to new to networking so I thought I'd start with something simple so I was trying to make a simple C++ echo server. I'm using PuTTY for testing. When I connect to the server through PuTTY I get a PuTTY error of Invalid padding length received packet When I check the server console it says that the PuTTY client connected but disconnected immediatelly. Here's my code. #include <stdlib.h> #include <WS2tcpip.h> //includes the winsock file as well #include <string> #pragma comment (lib,"ws2_32.lib") #define PORT 17027 int main() { //Initialize winsock WSADATA wsData; WORD ver = MAKEWORD(2, 2); int wsOK = WSAStartup(ver, &wsData); if (wsOK != 0) { std::cout << "Can't initialize wonsock! Quitting" << std::endl; return 0; } //Create a socket SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, 0); if (listenSocket == INVALID_SOCKET) { std::cout << "Can't create socket! Quitting" << std::endl; return 0; } //Bind the socket to an ip address and port sockaddr_in hint; hint.sin_family = AF_INET; hint.sin_port = htons(PORT); hint.sin_addr.S_un.S_addr = INADDR_ANY; bind(listenSocket, (sockaddr *)&hint, sizeof(hint)); //Tell Winsock the socket is for listening listen(listenSocket, SOMAXCONN); //Wait for connection sockaddr_in client; int clientSize = sizeof(client); SOCKET clientSocket = accept(listenSocket, (sockaddr*)&client, &clientSize); if (clientSocket == INVALID_SOCKET) { std::cout << "Cant accept client! Quitting" << std::endl; return 0; } char host[NI_MAXHOST]; // Client's remote name; char service[NI_MAXHOST]; // Client's (i.e. port) the client is connected on ZeroMemory(host, NI_MAXHOST); ZeroMemory(service, NI_MAXHOST); if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXHOST, 0) == 0) // try to get name of client { std::cout << host << " connected on port " << service << std::endl; } else { inet_ntop(AF_INET, &client.sin_addr, host, NI_MAXHOST); //get address of client std::cout << host << " connected on port " << ntohs(client.sin_port) << std::endl; } //Close listening socket closesocket(listenSocket); //While loop: accept and echo message back to client char buf[4096]; while (true) { ZeroMemory(buf, 4096); //Wait for client to send data int bytesReceived = recv(clientSocket, buf, 4096, 0); if (bytesReceived == SOCKET_ERROR) { std::cerr << "Error in recv(). Quitting" << std::endl; break; } if (bytesReceived == 0) { std::cerr << "Client disconnected" << std::endl; break; } //Echo message back to client send(clientSocket, buf, bytesReceived + 1, 0); } //Close the socket closesocket(clientSocket); //Cleanup winsock WSACleanup(); return 0; }
It looks like you are trying to connect with SSH. Your code is not an SSH server. To connect to a raw socket server with PuTTY, you need to select the "Raw" connection type.
69,329,072
69,329,281
Vector of Pairs of integers
I'm asked to get a value N and I will then get N pairs of values. These pairs will be the size of my 2D array, and this 2D array's elements will range from 1 to the size of the 2D array. Sample input: N = 2 Two pairs of values are (2,3) (3,4) Sample output: {(1,2,3),(4,5,6)} {(1,2,3,4),(5,6,7,8),(9,10,11,12)} The below code is what I have tried. I'm still a beginner so kindly help me. #include<bits/stdc++.h> using namespace std; makeArray(int a, int b){ int arr[a][b]; int temp = 1; cout<<"["; for(int i=1; i<=a; i++){ cout<<"["; for(int j=1; j<=b; j++){ cout<<temp<<","; } cout<<"]"; } cout<<"]"; } int main() { int n; cin>>n; int a,b; vector<pair<int,int>> ip; for(int i=0; i<n; i++){ cin>>a; cin>>b; ip.push_back(make_pair(a,b)); } for (int x=0; x<n; x++) { makeArray(ip.first, ip.second); cout<<endl; } return 0; }
I did not quite get what the task is, but I fixed few errors in the code, so that it runs and satisfies the sample you've provided. #include<bits/stdc++.h> using namespace std; void makeArray(int a, int b){ //int arr[a][b]; int temp = 0; cout<<"["; for(int i=1; i<=a; i++){ cout<<"["; if (1 <= b) cout << ++temp; for(int j=2; j<=b; j++){ cout << "," << ++temp; } cout<<"]"; } cout<<"]"; } int main() { int n; cin>>n; int a,b; vector<pair<int,int>> ip; for(int i=0; i<n; i++){ cin>>a; cin>>b; ip.push_back(make_pair(a,b)); } for (int x=0; x<n; x++) { makeArray(ip[x].first, ip[x].second); cout<<endl; } return 0; } To be more specific, in the main() function, second for loop: for (int x=0; x<n; x++) { //makeArray(ip.first, ip.second); makeArray(ip[x].first, ip[x].second); cout<<endl; } You forgot to use the brackets operator [] to access the elements of the vector. In the makeArray function: arr variable is not used. Forgot the return type (void). You do not increment temp variable, so you end up printing 1 instead of a range form 1 to a * b You have a trailing comma after printing the last integer Fix: // return type is required void makeArray(int a, int b){ //int arr[a][b]; variable not used. //temp is later incremented, so the first //element printed will be 1. int temp = 0; cout<<"["; for(int i=1; i<=a; i++){ cout<<"["; //We do not know, if we only need 1 //integer printed, so to not have a trailing //comma at the end, we print the first integer //outside the array if (1 <= b) cout << ++temp; //because the first integer is already printed, //we start from the second for(int j=2/*1*/; j<=b; j++){ //cout<<temp<<","; cout << "," << ++temp; } cout<<"]"; } cout<<"]"; } Input: 2 2 3 3 4 Output: [[1,2,3][4,5,6]] [[1,2,3,4][5,6,7,8][9,10,11,12]]
69,329,900
69,330,260
Data in 2D array is Gone
I'm having a hard time with this 2D array in CPP. I tried following this link, but it did not solve my problem. In the saveApToEeprom() function I save two strings. This works fine. Then i want to read from the EEPROM using getConfigForEeprom(). This is where things go wrong. The function getConfigForEeprom() prints 2 times 32 bytes, that matches with what I see in saveApToEeprom(). But when the program goes into dumbDataEeprom() all the data in valueEeprom[1] seem to be gone, except for valueEeprom[0] is there. Does anyone know how to solve this issue? See below for my code main.cpp #include <eeprom_handler.h> void setup(){ initEeprom(); String ssid = "test"; String psw = "tset"; saveApToEeprom(ssid, psw); uint8_t** valuesOutEeprom = getConfigForEeprom(); dumbDataEeprom(valuesOutEeprom); } void loop() { } eeprom_handler.h #ifndef eeprom_handler_H #define eeprom_handler_H #include <Arduino.h> #include <String.h> #include <EEPROM.h> /* PARAMETERS EEPROM*/ #define PARAMETER_SIZE_IN_BYTES 32 #define PARAMETERS_EEPROM 2 #define BYTES_NEEDED_FROM_EEPROM (PARAMETER_SIZE_IN_BYTES*PARAMETERS_EEPROM) /* FUNCTIONS EEPROM */ void initEeprom(uint8_t nmrOfBytes = BYTES_NEEDED_FROM_EEPROM); uint8_t saveApToEeprom(String apSsid, String ApPsw); uint8_t** getConfigForEeprom(uint8_t nmrOfBytes = BYTES_NEEDED_FROM_EEPROM); void dumbDataEeprom(uint8_t** valuesOutEeprom); void clearEeprom(uint8_t nmrOfBytes = BYTES_NEEDED_FROM_EEPROM); #endif // eeprom_handler_H eeprom_handler.cpp /**************************************************************************/ /*! @brief Read data from the EEPROM @param nmrOfBytes uint8_t: total number of bytes of the EEPROM to read @return valueEeprom uint8_t[][]: [0-32][]) 32 bytes, should contain SSID [][0-32]) 32 bytes, should contain SSID */ /**************************************************************************/ // TODO reconstruct uint8_t to chars uint8_t** getConfigForEeprom(uint8_t nmrOfBytes){ if (Serial){ Serial.println("Class eeprom_handler, function: getConfigForEeprom"); } // init the 2D array uint8_t** valueEeprom = new uint8_t* [PARAMETERS_EEPROM]; for (uint8_t m = 0; m < PARAMETERS_EEPROM; m++){ valueEeprom[m] = new uint8_t[BYTES_NEEDED_FROM_EEPROM]; } for(uint8_t i = 0; i < PARAMETER_SIZE_IN_BYTES; i ++ ) { valueEeprom[0][i] = EEPROM.read(i); Serial.println(valueEeprom[0][i]); } for(uint8_t j = PARAMETER_SIZE_IN_BYTES; j < BYTES_NEEDED_FROM_EEPROM; j ++ ) { valueEeprom[1][j] = EEPROM.read(j); Serial.println(valueEeprom[1][j]); } return valueEeprom; } /**************************************************************************/ /*! @brief Serial print the data read from the EEPROM @param valuesOutEeprom uint8_t**: pointer to a uint8_t 2D array */ /**************************************************************************/ void dumbDataEeprom(uint8_t** valuesOutEeprom){ if (Serial){ Serial.println("Class eeprom_handler, function: dumbDataEeprom"); for (uint8_t i = 0; i < PARAMETERS_EEPROM; i++){ for (uint8_t j = 0; j < PARAMETER_SIZE_IN_BYTES; j++){ Serial.print(valuesOutEeprom[i][j]); } Serial.println(); } } } output (Serial) Class eeprom_handler, function: initEeprom Class eeprom_handler, function: saveApToEeprom Class eeprom_handler, function: clearEeprom 0 116 1 101 2 115 3 116 32 116 33 115 34 101 35 116 Class eeprom_handler, function: getConfigForEeprom 116 101 115 116 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 116 115 101 116 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Class eeprom_handler, function: dumbDataEeprom 1161011151160000000000000000000000000000 00000000000000000000000000000000
Solved I had a fault in my for loop in the function. I was writing the data of the EEPROM index [32-63] also to array index [32-62], but that needed to go array index [0-32] orginal: for(uint8_t j = PARAMETER_SIZE_IN_BYTES; j < BYTES_NEEDED_FROM_EEPROM; j ++ ) { valueEeprom[1][j] = EEPROM.read(j); Serial.println(valueEeprom[1][j]); } correct: for(uint8_t j = PARAMETER_SIZE_IN_BYTES; j < BYTES_NEEDED_FROM_EEPROM; j ++ ) { valueEeprom[1][j - PARAMETER_SIZE_IN_BYTES] = EEPROM.read(j); Serial.println(valueEeprom[1][j - PARAMETER_SIZE_IN_BYTES]); }
69,329,993
69,350,397
CreateDxgiSurfaceRenderTarget Keep failling
Okay I am creating A d2dwindow that can render another surfaces so i did that HR(D3D10CreateDevice ( NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, NULL, D3D10_SDK_VERSION, &D3dDevicePtr )); HR(D3dDevicePtr->QueryInterface(__uuidof(IDXGIDevice), (void**)&DXGIDevicePtr)); D3dDevicePtr->Release(); and after that IDXGISurface* DXGISurfacePtr; ID2D1RenderTarget* SurfaceRTPtr; //init the Surface { DXGI_SURFACE_DESC Desc = { 500, 500, DXGI_FORMAT_R32G32B32A32_UINT , {1 , 0} }; HR(DXGIDevicePtr->CreateSurface(&Desc, 1, DXGI_USAGE_RENDER_TARGET_OUTPUT, NULL, &DXGISurfacePtr)); Surfaces.emplace_back(DXGISurfacePtr); } //init the RT { FLOAT dpiX; FLOAT dpiY; D2dFacory->GetDesktopDpi(&dpiX, &dpiY); D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties( D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED), dpiX, dpiY ); HR(D2dFacory->CreateDxgiSurfaceRenderTarget(DXGISurfacePtr, props, &SurfaceRTPtr)); RTs.emplace_back(SurfaceRTPtr); } but the creating of rt keep failling i tried alot of values like tring every compination in D2D1_RENDER_TARGET_PROPERTIES but there is nothing and i tried that too float dpiX; float dpiY; D2dFacory->GetDesktopDpi(&dpiX, &dpiY); D2D1_RENDER_TARGET_PROPERTIES Prop = { D2D1_RENDER_TARGET_TYPE_DEFAULT, { DXGI_FORMAT_R32G32B32A32_UINT, D2D1_ALPHA_MODE_STRAIGHT }, dpiX, dpiY, D2D1_RENDER_TARGET_USAGE_NONE, D2D1_FEATURE_LEVEL_10 }; HR(D2dFacory->CreateDxgiSurfaceRenderTarget(DXGISurfacePtr, &Prop, &SurfaceRTPtr)); RTs.emplace_back(SurfaceRTPtr);
so i found the problem is the surface and the d2d api was not from the same dxgi so to solve that i followed https://learn.microsoft.com/en-us/windows/win32/direct2d/devices-and-device-contexts but there was some diffrances like it use core window not normal one and it alittle bit messy with api1 or 2 or 3 like ID2D1Device or ID2D1Device1 or ID2D1Device2 so take care when any one try to follow it and tnk every one who tried to help
69,330,082
69,429,495
How would one generalise `clearerr()` under C++?…
TL;DR I am aware that if a program listens for EOF (e.g. ^D) as a sign to stop taking input, e.g. by relying on a conditional like while (std::cin) {...}, one needs to call cin.clear() before standard input can be read from again (readers who'd like to know more, see this table). I recently learned that this is insufficient, and that the underlying C file descriptors, including stdin, need clearerr() to be run to forget EOF states. Since clearerr() needs a C-style file descriptor, and C++ operates mainly with std::basic_streambufs and the like (e.g. cin), I want to generalise some code (see below) to run clearerr() on any streambuf's associated C-style file-descriptor, even if that may not be stdin. EDITS (1&2): I wonder if stdin is the only ever file-descriptor that behaves like this (needing clearerr() to run) ...? If it isn't, then the following code should end the question of generalisation (idea pointed out by zkoza in their answer) As zkoza pointed out in their comment below, stdin is the only file-descriptor that would, logically, ever need such treatment (i.e. clearerr()). Checking whether a given C++ stream is actually really attached to *std::cin.rdbuf() is all that is needed: std::istream theStream /* some stream with some underlying streambuf */ if (theStream.rdbuf() == std::cin.rdbuf()) clearerr(stdin); Background I'm writing a tool in C++ where I need to get multiple lines of user input, twice. I know there are multiple ways of getting multiline input (e.g. waiting for double-newlines), but I want to use EOF as the user's signal that they're done — not unlike when you gpg -s or -e. After much consultation (here, here, and on cppreference.com), I decided to use... (and I quote the third): [the] idiomatic C++ input loops such as [...] while(std::getline(stream, string)){...} Since these rely on std::basic_ios::operator bool to do their job, I ensured that cin.rdstate() was cleared between the first and second user-input instructions (using cin.clear()). The gist of my code is as follows: std::istream& getlines (std::basic_istream<char> &theStream, std::vector<std::string> &stack) { std::ios::iostate current_mask (theStream.exceptions()); theStream.exceptions(std::ios::badbit); std::string &_temp (*new std::string); while (theStream) { if (std::getline(theStream, _temp)) stack.push_back(_temp); // I'd really like the input broken... // ... into a stack of `\n`-terminated... // ... strings each time } // If `eofbit` is set, clear it // ... since std::basic_istream::operator bool needs `goodbit` if (theStream.eof()) theStream.clear(theStream.rdstate() & (std::ios::failbit | std::ios::badbit)); // Here the logical AND with // ... (failbit OR badbit) unsets eofbit // std::getline sets failbit if nothing was extracted if (theStream.fail() && !stack.size()) { throw std::ios::failure("No input recieved!"); } else if (theStream.fail() && stack.size()) { theStream.clear(theStream.rdstate() & std::ios::badbit); clearerr(stdin); // the part which I want to generalise } delete &_temp; theStream.exceptions(current_mask); return theStream; }
This does what you need: #include <iostream> int main() { std::cin.sync_with_stdio(true); char c = '1', d = '1'; std::cout << "Enter a char: \n"; std::cin >> c; std::cout << (int)c << "\n"; std::cout << std::cin.eof() << "\n"; std::cin.clear(); clearerr(stdin); std::cout << std::cin.eof() << "\n"; std::cout << "Enter another char: \n"; std::cin >> d; std::cout << (int)d << "\n"; std::cout << std::cin.eof() << "\n"; } It works because C++'s std::cin is tied, by default, with C's stdin (so, the first line is actually not needed). You have to modify your code to check if the stream is std::cin and if so, perform clearerr(stdin); EDIT: Actually, sync_with_stdio ensures only synchronization between the C and C++ interfaces, but internally they work on the same file descriptors and this may be why clearerr(stdin); works whether or not the interfaces are tied by sync_with_stdio EDIT2: Does these answer your problem? Getting a FILE* from a std::fstream https://www.ginac.de/~kreckel/fileno/ ?
69,330,184
69,330,282
How to access values from a pointer-to-array in C++
I am using the dereference operator but I don't seem to getting values of x. #include <iostream> using namespace std; class Array { public: int* get() { int x[] = { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 }; int *r; r = x; return r; } }; int main() { Array arr; int *temp = arr.get(); for (int i = 0; i < 10; ++i) { cout << temp[i] << " "; } } This prints out 31 32765 0 0 0 0 -1989689609 32624 -989639072 32765 rather than 31 45 39 32 9 23 75 80 62 9
When a variable, that is allocated on stack, goes out of scope, it gets destroyed. In your example functionArray::get: int* get() { int x[] = { 31, 45, 39, 32, 9, 23, 75, 80, 62, 9 }; int *r; r = x; return r; } variable x gets destroyed. If you don't want this to happen, you can mark your variable with a static keyword: static int x[] = ... or allocate it on heap int* x = new int[10]. If you use the latter, make sure you free the memory when it's no longer used or use smart pointers.
69,330,253
69,339,645
what are the correct arguments for D2D1Factory::CreateDxgiSurfaceRenderTarget()
i want create direct2D render target that will render on screen with direct3D, so i try to call the D2D1Factory::CreateDxgiSurfaceRenderTarget() funtion to make a direct2D render target, but it keep fails. The error i get from HRESULT is invalid argument-s passed. I tried these 3 codes FLOAT dpiX; FLOAT dpiY; factory->GetDesktopDpi(&dpiX, &dpiY); D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties( D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED), dpiX, dpiY ); hr = factory->CreateDxgiSurfaceRenderTarget(dxgiBackbuffer, &props, &d2dRenderTarget); if (FAILED(hr)) { //i get the error here } D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties( D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED) ); hr = factory->CreateDxgiSurfaceRenderTarget(dxgiBackbuffer, &props, &d2dRenderTarget); if (FAILED(hr)) { //i get the error here } D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(); hr = factory->CreateDxgiSurfaceRenderTarget(dxgiBackbuffer, &props, &d2dRenderTarget); if (FAILED(hr)) { //i get the error here } i assume the error coming from D2D1_RENDER_TARGET_PROPERTIES, but what are the correct arguments to make it work? here is how i get the dxgiBackbuffer IDXGISurface* dxgiBackbuffer; hr = swapchain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackbuffer)); i get the swapchain from the main application that running direct3D, so i will inject a DLL that will run direct2D In general this code is correct, i tested it on a direct3D project i made and it worked fine, but with this application that i try to inject the DLL it looks like it has something special, like some custom rendering properties? So in this case how can i get the correct properties?
After some research and as i haven't access to main application and also wasn't able to attach debugger, i finally found the issue. According to microsoft, when you call D3D11CreateDeviceAndSwapChain to create the D3D device, the flag D3D11_CREATE_DEVICE_BGRA_SUPPORT required for Direct2D interoperability with Direct3D resources. https://learn.microsoft.com/en-us/windows/win32/api/d3d11/ne-d3d11-d3d11_create_device_flag The application i try to hook into create its D3D device with flag 0.
69,330,295
69,330,753
Why does VSCode C++ yield 'explicit type is missing' warning for templates
I have the following code using namespace std; template <class T> vector<T> func(){ return vector<T>(100,0); } int main(){ auto test = func<int>(); cout << test[0] << " " << test.size() << endl; return 0; } It compiles without warning and runs correctly, but VSCode intelisense highlights test with the warning explicit type is missing ('int' assumed). Am I doing something wrong here? Changing the line to vector<int> test = func<int>(); makes VSCode happy, but I don't see why there would be any issue with auto here. Am I missing something? The only fix VSCode offers is to disable error squiggles, which I like in other instances.
The language version needed to be configured correctly. To resolve this I followed the configuration steps here: https://code.visualstudio.com/docs/cpp/config-mingw#_cc-configurations I ended up with the following global settings.json { "C_Cpp.default.cppStandard": "c++17", "C_Cpp.default.intelliSenseMode": "windows-gcc-x64", "C_Cpp.default.compilerPath": "C:\\...\\g++.exe" } Then after restarting VSCode it worked!
69,330,416
69,330,748
How to print substring contained between braces?
I'm writing a function, which is supposed to output whatever is between curly braces in string (e.g. hello world for text{hello world}). But it isn't outputting anything when I try running it. Do you have any idea what could be wrong? #include <iostream> #include <string> using namespace std; int main(){ start: std::string funct; std::cout << "-->"; std::cin >> funct; int temp = 0; //focus on what's down here V string word; if (funct.find("text") != string::npos) { for(int i=0; i<1; i){ if(funct.at(temp)=='}'){i=1;} else{ temp += temp; word = funct.at(temp + 5);} } cout<<word<<endl; } cout<<endl<<endl<<"=================================================="<<endl<<endl; goto start; return 0; } *Edit, 'funct' is the raw user input, and 'temp' is just a placeholder integer.
As I understand, you want a function that is parsing a string and printing whatever is within a construction like 'text{...}' Here is a few issues in your code: std::cin >> funct will only read a word (whitespace separated text). If you want to get an entire line, use std::getline(std::cin, yourString) You look for an occurrence of 'text', but do not save the index: if (funct.find("text") != string::npos) std::string::at() is indeed a safe way of accessing an element of a string, however your program may terminate with std::out_of_range exception if not handled. std::string::at() returns not a string, but a char& word = funct.at(temp + 5); Here's my implementation of a function, that finds text{...} construct in a string and prints the contents: #include <iostream> //using reference, so that the object is not copied void print_text(const std::string& string) { //starting and ending points of the needed text size_t start = string.find("text"), end; //if "text" is not found, exit function if (start == std::string::npos) return; //adding to start, so that it points to the last character of "test" start += sizeof("text") - 2; try { //ignoring all the spaces after "text" while (isspace(string.at(++start))); //testing for the open brace before the text if (string.at(start) != '{') return; end = start; ++start; //testing for the closing brace after the text needed while (string.at(++end) != '}'); //printing the substring if all the conditions are met std::cout << string.substr(start, end - start) << '\n'; } //any time we reach the end of the string, we bail printing nothing catch(std::out_of_range) { return; } } int main() { print_text(std::string("sample text{test1}")); print_text(std::string("sample space text {test2}")); print_text(std::string("empty sample text{}")); print_text(std::string("sample text{test4} some after")); print_text(std::string("sample forgot closing text{test5")); print_text(std::string("sample forgot starting texttest6}")); print_text(std::string("sample forgot starting text test7}")); print_text(std::string("sample extra characters text hi {test8}")); } Output: test1 test2 test4 Note: You can effectively ask a user input in the main function and pass the string in print_text function, it would work. Keep in mind, that it would only print the first occurrence of text{}, if you need any number of occurrences found, comment this reply.
69,330,428
69,330,979
Is there a binary search algorithm that takes a unary predicate rather than a search value?
I have this exercise: Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, input [3, 4, -1, 1] should give 2 and input [1, 2, 0] should give 3. You can modify the input array in-place.   My implementation: template <typename In_It> int missingPositiveInt(In_It first, In_It last){ first = std::find_if( first, last, [](int x){return x > 0;} ); if(first == last || *first > 1) return 1; for( auto next = first; (++next != last) && ( !(*next - *first > 1) ); ) ++first; return *first + 1; } int main(){ std::vector<int> v{5, 2, -1, 7, 0}; std::sort(v.begin(), v.end()); std::cout << missingPositiveInt(v.cbegin(), v.cend()) << '\n'; v = {2, -1, 1, 0}; std::sort(v.begin(), v.end()); std::cout << missingPositiveInt(v.cbegin(), v.cend()) << '\n'; v = {5, 2, -1, 7, 0}; std::sort(v.begin(), v.end()); std::cout << missingPositiveInt(v.cbegin(), v.cend()) << '\n'; v = {3, 4, -1, 1}; std::sort(v.begin(), v.end()); std::cout << missingPositiveInt(v.cbegin(), v.cend()) << '\n'; v = {1, 2, 0}; std::sort(v.begin(), v.end()); std::cout << missingPositiveInt(v.cbegin(), v.cend()) << '\n'; std::cout << '\n'; } The output: 1 3 1 2 3 The program works just fine but I use the algorithm std::find_if to find the first positive value in the sequence (sorted sequence) and that algorithm does a linear search. As long as the input sequence is already sorted I want to use some binary search algorithm to speed the process. I tried using std::binary_search but it requires an argument to be searched for. What I need is to get a version that takes a unary predicate and applies a binary search or any other faster algorithm to find the lowest positive value in the sequence so I can write: auto it = binary_search(first, last, [](int x){ return x > 0; }); Is it possible? Is my code fine or I need to modify it. So any suggestion, hint is highly appreciated.
Yes, std::partition_point does exactly what you want.
69,330,986
69,331,116
How to monitor clipboard changes in X11 Windows?
I am pretty much exhausted all the possibilities of finding an X11 API to perform the following thing. I have a thread which is trying to monitor for an event or notification to know when anything is copied into clipboard by any X11 client. I do not want to monitor a specific Atom Target (clipboard format), but generally looking for changes in clipboards. Once, I know that something has changed in the clipboard, I can dive in and perform XConvertSelection() on all the target formats (I want to request server to give me all the possible ways to convert the copied data), and futher process them into SelectionRequest event. Again, I want to generally get request for all the formats (thinking to enumerate between 1 to 1000 to check target Atoms), and not register changes for one specific format. Based on response from the server, if a particular atom is absent, I can check None as the property member, or else store other target Atom Names in a list. Can anyone help me with how to monitor for changes in Clipboard? Also, does iterating 1 to 1000 will guarantee exhaustive search of all possible format? Or is there a better way to do just that?
To monitor changes, use XFixes. With XCB it is used like: // Enable XFixes auto xfixes = xcb_get_extension_data(connection, &xcb_xfixes_id); // do not free! ev_selection_change_notify = xfixes->first_event + XCB_XFIXES_SELECTION_NOTIFY; auto *version = xcb_xfixes_query_version_reply(xcb_xfixes_query_version(connection, XCB_XFIXES_MAJOR_VERSION, XCB_XFIXES_MINOR_VERSION)); // Subscribe to clipboard notifications xcb_xfixes_select_selection_input(connection, root, clipboard, XCB_XFIXES_SELECTION_EVENT_MASK_SET_SELECTION_OWNER); // Event loop: auto *event = xcb_poll_for_event(connection); int etype = event->response_type & 0x7f; if (etype == ev_selection_change_notify) { auto *notification = reinterpret_cast<xcb_xfixes_selection_notify_event_t *>(event); ... } ... In Xlib it should be similar. To check the list of available targets, don’t loop to 1000! Simply query the TARGETS target, it should give you the list of valid targets for the clipboard content. There is a caveat, though: instead of “the” clipboard, X11 allow applications to use “selections” which can be tagged by arbitrary atoms. Of those CLIPBOARD is of primary interest but PRIMARY and (rarely used) SECONDARY are also there, as well as arbitrary selections for “private communication”. Reference: https://www.x.org/releases/X11R7.7/doc/xorg-docs/icccm/icccm.html#Use_of_Selection_Atoms
69,331,785
69,331,803
New type of auto-generated constructor in C++20
The code below doesn't compile on GCC 11 with -std=c++17, but does with -std=c++20: #include <iostream> #include <string> struct Foo { std::string s; int i; }; int main() { Foo foo("hello", 42); std::cout << foo.s << ' ' << foo.i << '\n'; } What's the feature in C++20 that enables this? What kind of constructor is generated by the compiler?
The C++20 feature being used here is the initialization of aggregates from parenthesis (P0960R3): This paper proposes allowing initializing aggregates from a parenthesized list of values; that is, Aggr(val1, val2) would mean the same thing as Aggr{val1, val2}, except that narrowing conversions are allowed. Here is an example from the above link: struct A { int a; int&& r; }; int f(); int n = 10; A a1{1, f()}; // OK, lifetime is extended A a2(1, f()); // well-formed, but dangling reference A a3{1.0, 1}; // error: narrowing conversion A a4(1.0, 1); // well-formed, but dangling reference A a5(1.0, std::move(n)); // OK So, for your code to work with C++17, just replace the parenthesis with braces. #include <iostream> #include <string> struct Foo { std::string s; int i; }; int main() { Foo foo{"hello", 42}; std::cout << foo.s << ' ' << foo.i << '\n'; }
69,331,986
69,332,146
How to push back a vector into a map<int, vector<int>>
What I want to do here is to create a map like this: 0 -> 0,1,...,4; 1-> 0,1,...,4; ... 9 -> 0,1,...,4; int main(){ map<int, vector<int>> m; for(int i=0; i<10; i++){ vector<int> temp; for(int j=0; j<5; i++){ temp.push_back(j); } m.insert({i, m.push_back(temp)}); } } But when I try to push back temp = {0,1,2,3,4} vector, it's giving me an error. I guess there is some problem in the syntax of the underlined line. Can you tell me how to solve this error?
std::map does not have a push_back() method. You need to insert the vector itself that you prepared, eg: int main(){ map<int, vector<int>> m; for(int i=0; i<10; i++){ vector<int> temp; for(int j=0; j<5; j++){ temp.push_back(j); } m.insert({i, temp}); } } Alternatively, use map::operator[] instead of map::insert(), let the map create each vector for you, eg: int main(){ map<int, vector<int>> m; for(int i=0; i<10; i++){ vector<int> &vec = m[i]; for(int j=0; j<5; j++){ vec.push_back(j); } } }
69,332,236
69,336,498
How does c++17 std::variant determine which type to use?
I am curious how std::variant works. From what i understand it is "basically" a union with an additional index variable. I am, however, confused how does it determine which type to forward the construction/assignment to efficiently. I have looked at it via godbolt.org and it does seem to be pretty efficient, even when copying from another variant. I have thought of how i would approach an implementation of a variant-like type, but the only way i thought of is to have some sort of helper functions that would forward constructor/assignemnt/destructor calls to the appropriate type based on an index argument. However that would be pretty inefficient with recurcive calls, wouldnt it? Another way would be to have a union with fixed types and whenever it would need to use a constructor/destructor etc. a big switch would decide which union member to use depending on the index variable, but that would require a lot of code bloat and would only work for fixed types. From what i can see on godbolt.org, gcc implementation of variant makes a call to std::__detail::__variant::__gen_vtable_impl, but i have not found any information on what it does. Also, how does it, for example, determine which variant type to use during construction if both of them are "convertible" from the passed argument type? cppreference says that the type must be convertible, but what if there are several possible variant types that are convertible? I have tried looking at gcc's stdlib implementation source but it is quite confusing, so i would appreciate if somebody explained it.
Another way would be to have a union with fixed types and whenever it would need to use a constructor/destructor etc. a big switch would decide which union member to use depending on the index variable, but that would require a lot of code bloat and would only work for fixed types. But this (morally) works fine for an arbitrary list of types. A switch with contiguous nonoverlapping cases is logically just indexing into your program's code. Therefore you can intuitively replace a switch with an array lookup: Extract the cases you'll switch into as functions, and then switching on the cases means indexing the array and calling into the result. switch(tag) { // effectively "go to line here + tag", so conceptually a lot like indexing case 0: ret = ...; break; case 1: ret = ...; break; ... } // <=> ret_t case0(args_t args) { return ...; } ret_t case1(args_t args) { return ...; } ... ret_t (*cases[])(args_t) = {case0, case1, ...}; ret = cases[tag](args); // and now it's literally indexing But generating a bunch of functions and constructing expressions according to patterns is just what templates do. template<std::size_t I, typename F, typename... Ts> decltype(auto) visit_case(F &f, std::variant<Ts...> &v) { return f(std::get<I>(v)); } // visit_case<0, F, T1, T2, ...>(f, v) assumes v is a T1 t1 and calls f(t1); // visit_case<1, F, T1, T2, ...>(f, v) assumes v is a T2 t2 and calls f(t2); // etc., so this template is capable of generating all the cases of a function on a variant as separate functions template<typename F, typename... Ts, std::size_t... Is> constexpr auto visit_cases_impl(std::index_sequence<Is...>) { return std::array{visit_case<Is, F, Ts...>...}; } template<typename F, typename... Ts> constexpr inline auto visit_cases = visit_cases_impl<F, Ts...>(std::index_sequence_for<Ts...>{}); // visit_cases<F, T1, T2, T3> = // std::array{visit_case<0, F, T1, T2, T3>, visit_case<1, F, T1, T2, T3>, visit_case<2, F, T1, T2, T3>} The "vtable" you were coming across was referring to the array of function pointers representing what to do with the possible alternatives. This table is all you need for a rudimentary std::visit: template<typename F, typename... Ts> decltype(auto) visit(F f, std::variant<Ts...> &v) { return visit_cases<F, Ts...>[v.index()](f, v); // <=> // switch(v.index()) { // case 0: return f(std::get<0>(v)); // case 1: return f(std::get<1>(v)); // ... // } } Now, for implementing std::variant, I think it's needed to have some super_visit that passes also the variant index as a template parameter to f, but otherwise it should be relatively straightforward. The copy/move constructors/assignments and destructor can all be written as such indexed visits. A complete example.
69,332,621
69,332,720
How to make a function that accepts code blocks
What I am seeking is a way to create a function that accepts a block of code as argument. I've seen this in boost's for-each loop But I can't find a way to do it myself I've searched but didn't find anything(probably my terminology was wrong) An example of what I want: int main() { DO_SOMETHING_FUNC(arg1, arg2, arg3) { //Block } }
This specific syntax can only be achieved with a macro. If possible, you should prefer a macro-less approach, i.e. passing a lambda to the function: do_something_func(foo, bar, [&] { }); The last parameter of my_for_each either needs to have a templated type: template <typename F> void my_for_each(/*blah, blah, */ F func) Or it can be std::function. To get this exact syntax (without ; after }), the macro needs to end with something like for (...) or if (...) (depending on how you want to use the code block), so the following braces become the body of this control statement. This might not be flexible enough in some cases, e.g. if you're writing a scope guard. If you change the syntax to have ; after }, things become easier. You can make your macro DO_SOMETHING_FUNC(x, y) expand to myHelper(x, y) ->* [&], where myHelper() returns an object with an overloaded binary operator (used ->* here, because it has the highest available priority). The braces following the macro become the lambda body, and the overloaded operator receives said lambda as the second argument.
69,332,664
69,386,313
Qt Insert two different QGraphicsWidgets in the same QGraphicsScene, setZValue is invalid
Calling collidingItems when two QGraphicsWidgets are visible overlapping, but returns null QGraphicsWidget0, QGraphicsWidget1 inherit from QGraphicsWidget. Eventually I see that icon1 is shown on top, how can I get icon1 to show on the bottom without changing the insertion order? icon0= new QGraphicsWidget0(); icon1= new QGraphicsWidget1(); scene.addItem(icon0); scene.addItem(icon1); icon1->setZValue(-1);
Thanks for the replies guys, I have solved the problem, I had set QGraphicsItem::ItemStacksBehindParent on some icons causing the other icons to look like setZValue() was not working.
69,332,862
69,332,927
Unhandled exception : An invalid parameter was passed to a function that considers invalid parameters fatal. in insertion sort
I am working on an insertion sort with vector in C++.However, I got an problem when I want to print the vector for the first 10 element. void insertion_sort(vector<int> &data, int n) { int temp; int i; int j; for (i = 1; i < n; i++) { temp = data[i]; j = i - 1; while (j >= 0 && data[j] > temp) { data[j + 1] = data[j]; --j; } data[j + 1] = temp; } } int main() { int size; cin >> size; vector<int> list; for (int i = 0; i < size; i++) { list.push_back(rand()); } insertion_sort(list, size); cout << "first 10 value in list is:"; for (int j = 0; j < 10; j++) { vector<int> arr(list.begin(), list.begin()+j); cout << arr.front() << ", "; } } The input of size is 1000. But, an error occurred with : Unhandled exception at 0x7927F2F6 (ucrtbased.dll): An invalid parameter was passed to a function that considers invalid parameters fatal. at the line of vector<int> arr(list.begin(), list.begin()+j); How can I fix this issue?
I fixed the problem with size < 10 (correct count being displayed and crash), language of message, printing out the values (main issue), use new line instead of ", " after last value, and also reduced scope of variables, return from main: #include <iostream> #include <vector> using namespace std; void insertion_sort(vector<int> &data, int n) { for (int i = 1, j; i < n; i++) { int temp = data[i]; j = i - 1; while (j >= 0 && data[j] > temp) { data[j + 1] = data[j]; --j; } data[j + 1] = temp; } } int main() { int size; cin >> size; vector<int> list; for (int i = 0; i < size; i++) { list.push_back(rand()); } int size2 = size < 10 ? size : 10; insertion_sort(list, size); cout << "first " << size2 << " value(s) in list: "; for (int j = 0; j < size2; j++) { cout << list[j]; if(j + 1 < size2) { cout << ", "; } } cout << "\n"; return 0; } Example output with input 3 and 20: first 3 value(s) in list: 846930886, 1681692777, 1804289383 first 10 value(s) in list: 304089172, 424238335, 596516649, 719885386, 783368690, 846930886, 1025202362, 1102520059, 1189641421, 1303455736 Perhaps you should validate that size > 0.
69,333,165
69,333,677
Mutual referencing among objects in C++
I want to create two objects with mutual member-references between them. Later it can be extended to e.g. closed loop of N referencing objects, where N is known in compile time. The initial attempt was with the simplest struct A lacking any constructors, which make it an aggregate (v simulates some payload): struct A { const A & a; int v = 0; }; struct B { A a1, a2; }; consteval bool f() { B z{ z.a2, z.a1 }; return &z.a1 == &z.a2.a; } static_assert( f() ); Unfortunately it is not accepted by the compilers due to the error: accessing uninitialized member 'B::a2' which is actually strange, because no real read access is done, only remembering of its address. Demo: https://gcc.godbolt.org/z/cGzYx1Pea The problem is solved after adding constructors in A, making it not-aggregate any more: struct A { constexpr A(const A & a_) : a(a_) {} constexpr A(const A & a_, int v_) : a(a_), v(v_) {} const A & a; int v = 0; }; Now all compilers accept the program, demo: https://gcc.godbolt.org/z/bs17xfxEs It is surprising that seemingly equivalent modification of the program makes it valid. Is it really some wording in the standard preventing the usage of aggregates in this case? And what exactly makes the second version safe and accepted?
B z{ z.a2, z.a1 }; attempts to copy-construct a1 and a2, rather than aggregate-initialize them with z.a2, z.a1 as first fields.1 B z{{z.a2, 0}, {z.a1, 0}}; works in GCC and Clang. MSVC gives error C2078: too many initializers, which looks like a bug. 1 Here, direct-list-initialization is performed for z, which in this case resolves to aggregate initialization, which in turn performs copy-initialization for each member, and: [dcl.init.general]/15.6.2 ... if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. So, because initializers z.a2, z.a1 have the same type as the corresponding members, the aggregate-ness of the members is ingored, and copy constructors are used.
69,333,549
69,334,015
C++: Allocating memory within multiple threads
this is more a general question rather than a specific coding problem. Does (and if yes, how) C++ avoid that multiple threads try to allocate the same memory adresses? For example: #include <vector> #include <thread> int main() { std::vector<int> x, y; std::thread do_work([&x] () { /* push_back a lot of ints to x */ }); /* push_back a lot of ints to y */ do_work.join() /* do more stuff */ } When the two vectors allocate memory because they reached their capacity, is it possible that both vectors try to allocate the same piece of memory since the heap is shared among threads? Is code like this unsafe because it potentially creates races?
Allocation memory (via malloc/new/HeapAlloc and such) are thread-safe by default as long as you've compiled you application against thread safe runtimes (which you will, unless you explicitly change that). Each vector will get its own slice of memory whenever they resize, but once a slice is freed any (other) thread could end up getting it the next time an allocation occurs. You could, however, mess things up if you replace your allocators. Like if you overload the "new operator" and you're no longer getting memory for a thread safe source. https://en.cppreference.com/w/cpp/memory/new/operator_new You could also opt to use a non-thread-safe version of malloc if you replace if via some sort of library-preload on Linux (Overriding 'malloc' using the LD_PRELOAD mechanism). But assuming you're not doing any of that, the default implementation of user-space allocators (new/malloc) are thread safe, and OS level allocators (VirtualAlloc/mmap) are always thread safe.
69,333,608
69,335,044
How to make threads with std::execution::par_unseq thread-safe?
I am reading C++ concurrency in action. It says that when you use std::execution::par, you can use mutex per internal element like below. #include <mutex> #include <vector> class X { mutable std::mutex m; int data; public: X() : data(0) {} int get_value() const { std::lock_guard guard(m); return data; } void increment() { std::lock_guard guard(m); ++data; } }; void increment_all(std::vector<X>& v) { std::for_each(v.begin(), v.end(), [](X& x) { x.increment(); }); } But it says that when you use std::execution::par_unseq, you have to replace this mutex with a whole-container mutex like below #include <mutex> #include <vector> class Y { int data; public: Y() : data(0) {} int get_value() const { return data; } void increment() { ++data; } }; class ProtectedY { std::mutex m; std::vector<Y> v; public: void lock() { m.lock(); } void unlock() { m.unlock(); } std::vector<Y>& get_vec() { return v; } }; void incremental_all(ProtectedY& data) { std::lock_guard<ProtectedY> guard(data); auto& v = data.get_vec(); std::for_each(std::execution::par_unseq, v.begin(), v.end(), [](Y& y) { y.increment(); }); } But even if you use second version, y.increament() in parallel algorithm thread also has data race condition because there is no lock among parallel algorithm threads. How does this second version with std::execution::par_unseq can be thread safe ?
It is only thread-safe because you do not access shared data in the parallel algorithm. The only thing being executed in parallel are the calls to y.increment(). These can happen in any order, on any thread and be arbitrarily interleaved with each other, even within a single thread. But y.increment() only accesses private data of y, and each y is distinct from all the other vector elements. So there is no opportunity for data races here, because there is no "overlap" between the individual elements. A different example would be if the increment function also accesses some global state that is being shared between all the different elements of the vector. In that case, there is now a potential for a data race, so access to that shared global state needs to be synchronized. But because of the specific requirements of the parallel unsequenced policy, you can't just use a mutex for synchronizing here. Note that if a mutex is being used in the context of parallel algorithms it may protect against different hazards: One use is using a mutex to synchronize among the different threads executing the for-each. This works for the parallel execution policy, but not for parallel-unsequenced. This is not the use case in your examples, as in your case no data is shared, so we don't need any synchronization. Instead in your examples the mutex only synchronizes the invocation of the for-each against any other threads that might still be running as part of a larger application, but there is no synchronization within the for-each itself. This is a valid use case for both parallel and parallel-unsequenced, but in the latter case, it cannot be achieved by using per-element mutexes.
69,333,609
69,333,884
Explaining C++ (C Binding Library) Function
I'm trying to understand a Function/Method in a Library in order to port it to Java however some parameters don't make any sense to me and reading the source code the library is based on is not helping. Function (Note the API has few comments (We can also ignore the calc handle since it's got a supplier method)) Ssr calc_ssr(CalcHandle *calc, NoteInfo *rows, size_t num_rows, float music_rate, float score_goal) { std::vector<NoteInfo> note_info(rows, rows + num_rows); auto skillsets = MinaSDCalc( note_info, music_rate, score_goal, reinterpret_cast<Calc*>(calc) ); return skillset_vector_to_ssr(skillsets); } NoteInfo Struct struct NoteInfo { unsigned int notes; float rowTime; }; MinaSDCalc // Function to generate SSR rating auto MinaSDCalc(const std::vector<NoteInfo>& NoteInfo, const float musicrate, const float goal, Calc* calc) -> std::vector<float> { if (NoteInfo.size() <= 1) { return dimples_the_all_zero_output; } calc->ssr = true; calc->debugmode = false; return calc->CalcMain(NoteInfo, musicrate, min(goal, ssr_goal_cap)); } Calc expected input file data (Only care about the #Notes: ...) Pastebin Question What is NoteInfo in calc_ssr, I don't know any C or C++ so the *rows to me just seems like a pointer to a Noteinfo instance, however the MinaSDCalc methods requires an Array/Vector which using a pointer to a single instance doesn't make sense to me (pairing this with the fact that NoteInfo needs another parameter rowTime which I think is time of Note occurrence in the file which means that value must not be constant otherwise the produced result would be inaccurate) Github Project: https://github.com/kangalioo/minacalc-standalone (The code alone may not explain enough but it's worth a try; best to look at API.h and discern what's used from there. Though I do warn you a lot of the Code is esoteric) Sorry if this doesn't make much sense but I've been looking into this since June/July and this API is the closest abstraction from the bare C++ code I could find.
NoteInfo * rows here is pass by pointer. So, rows actually is a pointer to an instance of type NoteInfo. This is one of the ways to pass arrays in c++ to a function. Since arrays are contiguous in memory so we can just increment the pointer by one and get the next element of the array. for example look at these three ways to do exactly one thing, parameter to pass an array to a function :- 1. void myFunction(int *param) {} 2. void myFunction(int param[10]) {} 3. void myFunction(int param[]) {} Look into this link for more understanding : https://www.tutorialspoint.com/cplusplus/cpp_passing_arrays_to_functions.htm Also search for pass by pointer and pass by reference to look into different ways of passing arguments in c++. 2.however the MinaSDCalc methods requires an Array/Vector which using a pointer to a single instance doesn't make sense to me: as to this question of yours, you can now see MinaSDCalc is actually getting an array and not a single instance as passing the pointer is also one of the ways of passing an array in c++.
69,333,790
69,333,816
Is C++ compiler obligated to generate 'ret' instruction for a function without 'return' statement?
Recently I encountered a problem that a thread in my programe was somehow stopped (GDB indicates thread's state as STOPPED). I have spent a couple of days debugging. This problem happended after I changed the version of the compiler some days ago. Finally I found out that the problem happens because a function is defined with int return type but does not have a return statement. So the asm code of the function does not have a ret instruction. When it reaches the end of the funcion in runtime, since no ret instruction exists, execution continues on the next instruction which is in another funciton. This causes the thread being stopped. I have checked the asm code generated by the compiler of previous version, and the same function does have a ret instruction. In my experience, missing return statement in a function with non-void return type is not suggested, but should not results in thead stop. I want to know if I am wrong, or the compiler is wrong. My question is, for a normally ended (not ended by exception, call, jmp...) function with non-void return type, is the compiler obligated to generate a ret instruction or not. Does it have any C++ standards or C++ specifications illustrating the compiler behavoir in this case? I have done some search and found an answer for c# in this. How about for C++?
No. For any non-void function except main, if there is any path through the function that does not return, your program exhibits undefined behaviour if that path is taken at runtime. Then the compiler is allowed to do whatever it feels like. Generally this results in just a missing ret statement but I have seen much weirder effects. The standard specifies this in [stmt.return].2: [..] Flowing off the end of a constructor, a destructor, or a non-coroutine function with a cv void return type is equivalent to a return with no operand. Otherwise, flowing off the end of a function other than main (6.9.3.1) or a coroutine (9.5.4) results in undefined behavior. (emphasis added)
69,333,792
69,333,839
How to create objects based on user input?
I want to make a program which creates an object each time user enters an employee name. The object should be named according to the name of the employee. #include <iostream> using namespace std; class employee { public: int salary; int ma = 300; float da = 1.25; float hra = 0.15; }; int main() { char name; cin >> name; employee:("name"); } How can do this? using this piece of code throws an error main.cpp:18:13: warning: expression result unused [-Wunused-value] employee:("name"); ^~~~~~ 1 warning generated.
Give the employee class a name field, and a constructor to initialize it #include <iostream> #include <string> using namespace std; class employee { public: string name; int salary = 0; int ma = 300; float da = 1.25; float hra = 0.15; employee(string name) : name(name) {} }; int main() { string name; cin >> name; employee emp(name); }
69,333,936
69,334,256
std::vector::emplace_back with a POD C++
I have a fairly bog standard Vector4 struct (the math kind not the C++ kind) which is a POD and is templated: template<typename T> struct Vector4 { T x, y, z, w; Vector4 operator+(const Vector4& other) const { return Vector4{ x + other.x, y + other.y, z + other.z, w + other.w }; } Vector4 operator-(const Vector4& other) const { return Vector4{ x - other.x, y - other.y, z - other.z, w - other.w }; } Vector4 operator*(const Vector4& other) const { return Vector4{ x * other.x, y * other.y, z * other.z, w * other.w }; } Vector4 operator/(const Vector4& other) const { return Vector4{ x / other.x, y / other.y, z / other.z, w / other.w }; } Vector4 operator+(const T& a) const { return Vector4{ x + a, y + a, z + a, w + a }; } Vector4 operator-(const T& a) const { return Vector4{ x - a, y - a, z - a, w - a }; } Vector4 operator*(const T& a) const { return Vector4{ x * a, y * a, z * a, w * a }; } Vector4 operator/(const T& a) const { return Vector4{ x / a, y / a, z / a, z / a }; } Vector4& operator+=(const Vector4& other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; } Vector4& operator-=(const Vector4& other) { x -= other.x; y -= other.y; z -= other.z; w -= other.w; return *this; } Vector4& operator*=(const Vector4& other) { x *= other.x; y *= other.y; z *= other.z; w *= other.w; return *this; } Vector4& operator/=(const Vector4& other) { x /= other.x; y /= other.y; z /= other.z; w /= other.w; return *this; } Vector4& operator+=(const T& a) { x += a; y += a; z += a; w += a; return *this; } Vector4& operator-=(const T& a) { x -= a; y -= a; z -= a; w -= a; return *this; } Vector4& operator*=(const T& a) { x *= a; y *= a; z *= a; w *= a; return *this; } Vector4& operator/=(const T& a) { x /= a; y /= a; z /= a; w /= a; return *this; } T& operator[](size_t index) { return *(reinterpret_cast<T*>(this) + index); } }; using Vector4f = Vector4<float>; using Vector4i = Vector4<int>; using Vector4i32 = Vector4<int32_t>; using Vector4ui32 = Vector4<uint32_t>; using Vector4i64 = Vector4<int64_t>; using Vector4ui64 = Vector4<uint64_t>; The problem I am having is that I cant make a std::vector of my Vector4 class. When I try the following: std::vector<ogl::Vector4f> vec; vec.emplace_back(1.0f, 2.0f, 3.0f, 4.0f); I get this compile error 'Vector4::Vector4': no overloaded function takes 4 arguments I have my own vector (C++ kind not math kind) class that I use and I tried using emplace_back with it but I got the same error. I also tried using and not using allocators (in my custom vector class) and have tried almost everything under the sun! I can fix this issue by defining a constructor, but then it doesn't become a POD anymore. Normal construction using brace initialization works fine so I don't what's wrong. If anyone can explain why this is happening/how to fix this (or if this is normal behaviour) it would be most appreciated.
emplace_back uses parentheses to initialize the value, which means a constructor is required to use it until C++20. C++20 introduced parenthesized initialization of aggregates, so you code becomes valid as is. Until then you can just do vec.push_back({1.0f, 2.0f, 3.0f, 4.0f});
69,333,938
69,334,218
Store multiple std arrays of variable size
I have different std::arrays with variable sizes, e.g. std::array<int, 5> array_one; std::array<int, 8> array_two; std::array<int, 2> array_three; The primary type is always the same (int in this example). Now I have to iterate over all those arrays and in order to do that with as little code as possible, I thought I would store them in e.g. one array and use it to access each array individually. Pseudocode: std::array array_wrapper = { array_one, array_two, array_three }; But that will not work as each array has a different size. Is there any storage type I can use to "collect" all arrays to iterate over them individually afterwards?
In case you just need to iterate, not to store arrays together, use std::span std::span<int> span[] = {array_one, array_two, array_three}; You may also flatten the views with std::views::join for(int &i : span | std::views::join) { ... } If arrays are constant, then std::span<int const> span[] = {array_one, array_two, array_three}; for(int const i : span | std::views::join) { ... }
69,334,823
69,334,895
Why access deleted pointer won't crash the program?
#include <iostream> #include<list> using namespace std; template <class T> class Ptr { public: Ptr() { a = nullptr; l.push_back(0); } std::list<int> l; void print_this() { cout<<this<<endl; } protected: int *a; }; int main() { Ptr<int> *ptr = new Ptr<int>(); delete ptr; //ptr = nullptr; //if uncomment this line will crash auto p = &(ptr->l); cout<<"p is "<<p<<endl; ptr->print_this(); ptr->l.push_back(1); cout<<"size is "<<ptr->l.size()<<endl; cout<<"end"; return 0; } I run code here: https://www.programiz.com/cpp-programming/online-compiler/ output is : p is 0x5628eb47deb0 0x5628eb47deb0 size is 2 end if I set ptr to nullptr after delete, it will crash at push_back. But still fine when I access the list. How is it even possible that I push data to a dangling pointer without crashing it??
When you have a pointer to a class, and call a non-virtual function on it, whatever the address is at the pointer will be considered the this pointer. Even if it is zero. As long as you don't try to access members at that address, you should have no problem printing the this poniter. struct A { void printThis() { printf("%d\n", this); } }; int _tmain(int argc, _TCHAR* argv[]) { A * a = (A*) 777; a->printThis(); // will print 777 a = NULL; a->printThis(); // will print 0 return 0; } When you delete a pointer and don't set its address to null, the previous address value is kept. Accessing a deleted pointer is undefined behavior. It is not required to crash. It just may be that the random data that you are pointing to has some meaning somewhere else in the program. It may even be your old data. Deleting a pointer tells the system it can reuse that memory, but it may not have had time to reuse it yet, and so the old data could still be visible. Finally your program crashes when you uncomment your line because that sets ptr = 0, and &(0x0000000->l) is an invalid memory reference.
69,334,861
69,335,095
Should class be not trivially destructible, if standard specifies that it has a destructor?
Consider std::latch [thread.latch.class]: namespace std { class latch { public: static constexpr ptrdiff_t max() noexcept; constexpr explicit latch(ptrdiff_t expected); ~latch(); latch(const latch&) = delete; latch& operator=(const latch&) = delete; void count_down(ptrdiff_t update = 1); bool try_wait() const noexcept; void wait() const; void arrive_and_wait(ptrdiff_t update = 1); private: ptrdiff_t counter; // exposition only }; } Note that destructor is present. This means that this should hold: static_assert(std::is_trivially_destructible_v<std::latch> == false); However, it is opposite for the implementations (MSVC STL, libstdc++, libc++): https://godbolt.org/z/6s8173zTc Is this: Implementation freedom (implementations are correct, is_trivially_destructible_v may be true or false) Implementation defect in every implementation (implementation should have non-trivial destructor for std::latch) Standard defect (Standard shouldn't have specified std::latch to have non-trivial destructor) ?
This is implementation freedom. The C++ standard defines the class, the implementation of the class is up, well, to the implementation. There are some classes where the standard explicitly mandates a trivial destructor. For example, if an existing class is trivially destructible then its std::optional also must be trivially destructible. This needs to be spelled out. Therefore, unless somewhere there is an explicit statement that the class is or is not trivially constructible, then this is up to the implementation (where possible). Looking at gcc's header file: it doesn't merely declare, but it explicitly defines the destructor: ~latch() = default; Based on that the compiler can work out that the whole thing is trivially destructible.
69,335,019
69,347,055
Is there an alternative on nested loop for displaying possible combination in range of n?
I created some code where, whenever you put number in pinCombo(x) (for example pinCombo(3)), the output will be: 000 001 002 … until it reaches 999. So, pinCombo(4) output will be: 0000 0001 .... .... 9999 Here's my code: #include <iostream> using namespace std; void pinCombo(int x) { int a,b,c,d,e,f,g,h,i,j; if(x>=1) for (a = 0;a<10;a++) { if(x>=2) for (b = 0;b<10;b++) { if(x>=3) for (c = 0;c<10;c++) { if(x>=4) for (d = 0;d<10;d++) { if(x>=5) for (e = 0;e<10;e++) { if(x>=6) for (f = 0;f<10;f++) { if(x>=7) for (g = 0;g<10;g++) { if(x>=8) for (h = 0;h<10;h++) { if(x>=9) for (i = 0;i<10;i++) { if(x>=10) for (j = 0;j<10;j++) { cout<<a<<b<<c<<d<<e<<f<<g<<h<<i<<j<<endl; }if(x==9)cout<<a<<b<<c<<d<<e<<f<<g<<h<<i<<endl; }if(x==8)cout<<a<<b<<c<<d<<e<<f<<g<<h<<endl; }if(x==7)cout<<a<<b<<c<<d<<e<<f<<g<<endl; }if(x==6)cout<<a<<b<<c<<d<<e<<f<<endl; }if(x==5)cout<<a<<b<<c<<d<<e<<endl; }if(x==4)cout<<a<<b<<c<<d<<endl; }if(x==3)cout<<a<<b<<c<<endl; }if(x==2)cout<<a<<b<<endl; }if(x==1)cout<<a<<endl; } } using namespace std; int main() { pinCombo(3); return 0; } Is there a way to create a program like this without using nested loops or without using many variables?
Here's a solution using setwidth and setfill. #include <iostream> #include <iomanip> #include <cmath> using namespace std; void pinCombo(int x){ for (int i = 0; i < pow(10, x); i++){ cout << setw(x) << setfill('0') << i << endl; } } int main(){ pinCombo(3); return 0; }
69,335,200
69,335,302
Variadic template function
I was trying to code a function that takes unbounded number of arguments in C++. To do so, I had to try it in the function below. With two arguments : unsigned int bitClear(uint32_t &bitNum, unsigned int pos) { bitNum = bitNum & (~(1 << pos)); return bitNum; } But with unbounded number of arguments, I didn't want to use the cstdarg from STL. Because, at each call, I have to give the number of arguments the function works with, followed by the arguments. So, I was hoping to use variadic template function. I searched for solution here and there, but the answers I got from Stack Overflow did not really come close to what I was looking for. So, by looking at "C++ Templates The Complete Guide" on chapter 4 (Variadic Templates) I got some useful information. // base case template<typename T> decltype(auto) bitClear(T &t, unsigned int pos) { t = t & (~(1 << pos)); return t; } // general case template<typename T1, typename T2, typename... Args> decltype(auto) bitClear(T1 &t1, T2 pos2, Args... args) { t1 = t1 & ~((1 << pos2)|(1 << bitSet(args...))); // recursive call return t1; } This approach uses a recursive call to unpack the rest of the arguments in the function. Unfortunately, I did not get everything right though. #include <iostream> #include <bitset> #define MAX 16 using namespace std; // the template functions are defined here int main(int argc, char** argv) { unsigned int u = 0b11111111111111; // the same as 0xFFFF; cout << "Clearing multiple bits at once : " << bitset<MAX>(bitClear(u, 2, 5)) << "\n"; cout << "Clearing multiple bits at once : " << bitset<MAX>(bitClear(u, 2, 5, 10)) << "\n"; cout << "Clearing multiple bits at once : " << bitset<MAX>(bitClear(u, 2, 5, 7, 10, 11)) << "\n"; return 0; } The return : Clearing multiple bits at once : 0011111111011011 Clearing multiple bits at once : 0011111111011011 Clearing multiple bits at once : 0011111111011011 Which is not correct, the expected result is : Clearing multiple bits at once : 1111111111011011 Clearing multiple bits at once : 1111101111011011 Clearing multiple bits at once : 1111001101011011 After changing the above code by : ///** Base case **/// template<typename T> decltype(auto) bitClear(T &par1) { return par1; } ///**General case **/// template<typename T1, typename... Args> decltype(auto) bitClear(T1 t1, Args... args) { t1 = t1 & ~(1 << bitClear(args...)); return t1; } I am unable to get the desired result and I can't even find where did I go wrong. Does anyone out there has any idea to help me overcome this hurdle?
Something along these lines, perhaps: template <typename Val, typename ... Pos> Val& bitClear(Val& v, Pos... pos) { ((v &= ~(1 << pos)), ...); return v; } Demo
69,335,493
69,335,619
What is the difference between returning auto&& and decltype(auto)?
I am trying to make template wrapper function, that should forward parameters and return value. And I can't decide what is better to use auto&& or decltype(auto) for return type. I've read Scott Meyers article and understood that it is necessary to return decltype(auto) compared to auto not to strip ref_qualifiers. As far as I understand the same argument works for using auto&& over auto. Now I have following questions: Am I right, that there is no difference between decltype(auto) and auto&& when we return reference to object? What happens if we return rvalue object, like: return int{};? Will return value be dangling reference? What is the difference between decltype(auto) and auto&&? What better fits as forward return type?
What is the difference between decltype(auto) and auto&&? decltype(auto) covers three cases. When returning lvalues, the return type would be T& (lvalue-reference); for xvalues, the return type would be T&& (rvalue-reference); for prvalues, the return type would be T (non-reference, i.e. return by-value). auto&& covers only two cases. When returning lvalues, the return type would be T& (lvalue-reference); for rvalues, including xvalues and prvalues, the return type would be T&& (rvalue-reference). (Forwarding reference is always a reference.) What happens if we return rvalue object, like: return int{};? Will return value be dangling reference? For auto&& the return type is rvalue-reference, so yes, the returned reference is always dangling. For decltype(auto) the return type is non-reference then no such trouble.
69,335,535
69,412,274
Using a basic function of CGAL, e.g. `square`
I am starting to work my way through CGAL and have a question about the Algebraic foundations package. How do you use the square function defined here? I tried the following // tmp.cpp #include <CGAL/number_utils.h> int main() { double dist = 0.002; auto sq_dist = CGAL::square(dist); return 0; } The compiler throws the following error message $ make tmp Consolidate compiler generated dependencies of target tmp [ 14%] Building CXX object CMakeFiles/tmp.dir/tmp.cpp.o In file included from /home/USER/info/cgal/tmp/tmp.cpp:1: /home/USER/info/cgal/Algebraic_foundations/include/CGAL/number_utils.h: In instantiation of ‘typename CGAL::Algebraic_structure_traits<Type_>::Square::result_type CGAL::square(const AS&) [with AS = double; typename CGAL::Algebraic_structure_traits<Type_>::Square::result_type = CGAL::Null_tag; typename CGAL::Algebraic_structure_traits<Type_>::Square = CGAL::Null_functor]’: /home/USER/info/cgal/tmp/tmp.cpp:5:30: required from here /home/USER/info/cgal/Algebraic_foundations/include/CGAL/number_utils.h:71:18: error: no match for call to ‘(CGAL::Algebraic_structure_traits<double>::Square {aka CGAL::Null_functor}) (const double&)’ 71 | return square( x ); | ~~~~~~^~~~~ make[3]: *** [CMakeFiles/tmp.dir/build.make:146: CMakeFiles/tmp.dir/tmp.cpp.o] Error 1 make[2]: *** [CMakeFiles/Makefile2:83: CMakeFiles/tmp.dir/all] Error 2 make[1]: *** [CMakeFiles/Makefile2:90: CMakeFiles/tmp.dir/rule] Error 2 make: *** [Makefile:124: tmp] Error 2 It is mentioned in this github issue. Update: Following the comment by @MarcGlisse I changed the header include to // tmp.cpp #include <CGAL/number_utils.h> #include <CGAL/basic.h> int main() { double dist = 0.002; auto sq_dist = CGAL::square(dist); return 0; } Compilation runs through smoothly but linking throws new errors $ make tmp [ 14%] Building CXX object CMakeFiles/tmp.dir/tmp.cpp.o [ 28%] Linking CXX executable tmp /usr/bin/ld: CMakeFiles/tmp.dir/tmp.cpp.o: in function `main': /home/USER/info/cgal/STL_Extension/include/CGAL/exceptions.h:88: multiple definition of `main'; /usr/bin/ld: DWARF error: section .debug_str is larger than its filesize! (0x32f0bc2 vs 0x2447b28) /usr/bin/ld: DWARF error: section .debug_str is larger than its filesize! (0x32f0bc2 vs 0x2447b28) /usr/bin/ld: DWARF error: section .debug_str is larger than its filesize! (0x32f0bc2 vs 0x2447b28) ... The referenced line STL_Extension/include/CGAL/exceptions.h:88 can be found here. Update: I found the issue (see my answer) but it doesnt make sense to me. Why am I not able to have multiple main functions in different files in the same folder? I built the following way cd ${CGAL_DIR}/tmp cgal_create_CMakeLists -s tmp cmake -DCMAKE_BUILD_TYPE=Debug . make tmp
The issue arises because of the -s tmp argument. The solution is to call it in either of the following formats cgal_create_CMakeLists tmp cgal_create_CMakeLists The documentation gives an explanation $ cgal_create_CMakeLists -h Usage: cgal_create_CMakeLists [-s source] ... ... -s source If this parameter is given the script will create one single executable for 'source' with all source files; otherwise it creates one executable for each main'ed source. ... There is no reasonable way to create one executable for files containing multiple main functions.
69,335,705
69,335,755
Increment default constructed int in the unordered map
I have unordered map of counters, e.g: std::unordered_map<std::string, std::size_t> counters_; Do i need to manually create a value before trying to increment it? Will the next line be considered undefined behavior? std::unordered_map<std::string, std::size_t> counters_; counters_["non_existing_key"] += 1;
By using the std::map::operator[], you're creating a new value in the map if it didn't exist before. Furthermore, the value new will be value-initialized, so incrementing the value is well-defined.
69,336,152
69,349,134
install pytorch c++ api CUDA11.4 for ubuntu
I'm trying to use the PyTorch c++ API on an ubuntu 18.04. I've installed CUDA 11.4 and cuDNN 8.2.4.15. The source I'm compiling is available here. compiling CUDA with nvcc works and the cuDNN installation test succeeds. But I am unable to find a good documentation for installing and compiling projects with PyTorch c++ api on Ubuntu. Do you know any god ones? system configurations: OS: ubuntu 18.04 GPU: 1 x NVIDIA Tesla P4 Machine Type: n1-standard-2 (2 vCPUs, 7.5 GB memory) on google cloud console CUDA: 11.4 cuDNN: 8.2.4.15
I used the next ones to install on Ubuntu 16, it can be helpful for you. PyTorch C++ API Ubuntu Installation Guide tutorial to compile and use pytorch on ubuntu 16.04 Also can it will be util to refer the official documentation to use PyTorch c++ for Linux systems and the GCPdocumentation.
69,336,301
69,336,345
Use C++20 Concept to constrain template parameter
I want to use concepts to replace a design which currently uses SFINAE (enable_if). To simplify, I have created a simpler example which shows an identical problem: template<typename T> concept smallerThanPointer = sizeof(T) < sizeof(void*); template<typename T> concept notSmallerThanPointer = !smallerThanPointer<T>; template<smallerThanPointer T> class MyClass { public: MyClass() { std::cout << "MyClass[smallerThanPointer]\n"; } }; template<notSmallerThanPointer T> class MyClass { public: MyClass() { std::cout << "MyClass[...]\n"; } }; int main() { MyClass<int[8]> c1; return 0; } But my compiler (g++-11) will not accept this syntax because it thinks I'm redeclaring MyClass. Also this example is not possible: template<typename T> class MyClass requires smallerThanPointer<T> { public: MyClass() { std::cout << "MyClass[smallerThanPointer]\n"; } }; template<typename T> class MyClass { public: MyClass() { std::cout << "MyClass[...]\n"; } }; All examples I have found online with concepts only discuss how to apply concepts to function parameters. So is it possible at all to do with a class?
The correct syntax for the partial template specialization for constraints should be: template<typename T> concept smallerThanPointer = sizeof(T) < sizeof(void*); template<class T> class MyClass { public: MyClass() { std::cout << "MyClass[...]\n"; } }; template<class T> requires smallerThanPointer<T> class MyClass<T> { public: MyClass() { std::cout << "MyClass[smallerThanPointer]\n"; } }; Demo.
69,336,491
69,354,434
C++ Linking SQLite to Visual Studio 2019 project
I am trying to use SQLite with Visual Studio 2019. I downloaded "amalgamation" package and included"sqlite3.h" and "sqlite3.c" files to the project but I get errors(link to pastebin below) #include "sqlite3.h" #include "sqlite3.c" https://pastebin.com/6T5HMnyh What am I doing wrong?
I had hit this same thing today. As S.M. stated, you don't want to include the .c file anywhere in this process. You should include the sqlite3.h file and follow these instructions. I found that I not only had to download the amalgmation files but also the dll files (for either x64 or x86 depending on your flavor). I used https://sqlite.org/2021/sqlite-dll-win32-x86-3360000.zip, which gave me a .dll and a .def file. Copy them to your project directory and then open up a Visual Studio command prompt (terminal in the View menu). Browse to the directory that you've copied the files to and type LIB /DEF:sqlite3.def. This will create a library file for VS to use. Add this file to your project dependencies at Project Properties -> Configuration Properties -> Linker -> Input -> Additional Dependencies (you'll have to type it in manually as you can't browse). Compiling in Visual Studio should now work successfully.