question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
72,647,311
72,648,533
Template function with multiple parameters of same type
I'm trying to create a function that can take multiple parameters of the same type, passed in as a template. The number of arguments is known in compile time: struct Foo { int a, b, c; }; template <uint32_t argsCount, typename T> void fun(T ...args) // max number of args == argsCount { // ... // std::array...
If you change the function into a functor, you can introduce a parameter pack in the body of the type of the functor. First create a helper to turn <N, T> -> std::tuple<T, T, T, ..., T> (N times): template<std::size_t N, typename T> struct repeat { private: // enable_if<true, T> == type_identity<T> template<std...
72,647,450
72,649,109
Sending an email using curl c++
Im trying to send an email using curl c++, i managed to log in well and when i run the program it works fine, does not throw any error, but the email never comes. This is my code: #include <iostream> #include <curl/curl.h> static const char *payload_text = "Date: Mon, 29 Nov 2010 21:54:29 +1100\r\n" "To: " "mailto...
I found this to be a helpful starting point: https://curl.se/libcurl/c/smtp-mail.html There are two main problems with your code: Your read_function didn't keep track of how much of the payload has been read so it would keep giving the same content to libcurl over and over and never signal the end of the message. You ...
72,647,540
72,647,770
Cuda AtomicAdd for int3
In Cuda AtomicAdd for double can be implemented using a while loop and AtomicCAS operation. But how could I implement an atomic add for type int3 efficiently?
After further consideration, I'm not sure how an atomicAdd on an int3 would be any different than 3 separate atomicAdd operations, each on an int location. Why not do that? (An int3 cannot be loaded as a single quantity anyway in CUDA at the machine level. The compiler is guaranteed to split that into multiple loads,...
72,649,616
72,650,893
Why do I get an undefined reference although everything seems alright ? (C++ Mingw)
My problem is fairly trivial and simple, I am trying to write a packer and to do so I need to parse PE files, so I'm trying to use the C++ pe-parse library. I built it following the instructions and I'm now trying to link it to my simple main.cpp file: #include <pe-parse/parse.h> int main(int ac, char **av) { pepa...
You have a library produced by MSVC and you are trying to use g++ to link with it. Microsoft C++ compiler is not compatible with g++. Objects produced by one of them cannot use objects compiled by the other. They use vastly different ABIs and different standard library implementations. Your only option is to recompile ...
72,649,753
72,650,835
How to break circular dependency between exe and dll
A C++ app has this exe/dll layout: Main.exe, Framework.dll, PluginA.dll, PluginB.dll, ..., PluginN.dll Both Main.exe and Framework.dLL provide functions to the Plugin#.dll. The Plugins are depedent on Main.exe and Framework.dll, but not the other way around. Framework.dll depends on functions provided by Main.exe Now, ...
The usual solution to this (although it's usually used when two libraries have a circular dependency) is to create a 'dummy' version of one of them that defines all the relevant entry points but is not in any way dependent on the other and doesn't need to link against it. That can then be used as a kind of 'bootstrap'...
72,649,896
72,650,319
Passing templated friend function of a class to other function as parameter results in error
The following code demonstrates the problem. #include <functional> namespace test { template <class T> class A { public: friend auto foo(const A& obj) { return 1; } }; template <class Function, class... Args> void bar(Function f, Args&&... args) { const auto result = std::invoke(f, std::forward<Args>(args...
The problem is that the friend declaration for foo that you've provided is for a non-template function but while calling bar you're trying to use foo as a template. There are 2 ways to solve this: Method 1 Here we provide a separate parameter clause for foo. namespace test { template <class T> class A { pu...
72,650,120
72,663,851
How to select tuple elements by certain condition on types
I want to apply certain functionality to some elements of a tuple based on a given condition or constraint of the types. Below is a small dummy example where I want to call a callback function for all the elements in the tuple that holds an arithmetic type. In my current solution, I use std::apply and if constexpr on t...
It's really "as if" you are iterating over the full tuple. In general, the compiled program will only do that if it has to, or if all optimisations are disabled, to aid debugging. And indeed, starting from -O1 (gcc) or -O2 (clang), a slightly simplified version of your code compiles to "return 1;": main: mov ...
72,650,435
72,650,522
When GCC does not provide __cpp_lib_uncaught_exceptions feature?
Following piece of code does not work right on Alpine Linux: #ifndef __cpp_lib_uncaught_exceptions namespace std { int uncaught_exceptions() noexcept { return std::uncaught_exception(); } } #endif Source Error: [ 89%] Linking CXX executable AdsLibTest.bin /usr/lib/gcc/x86_64-alpine-linux-musl/11.2.1/.....
Adding declarations to namespace std causes (with a few specific exceptions) undefined behavior. There is no reason that this should work, even if the compiler does correctly report that it doesn't provide std::uncaught_exceptions. In particular, if the standard library implementation supported std::uncaught_exceptions...
72,651,084
72,651,140
Why does std::set work with my free function operator<, but not my class member function operator<?
If I use the free function operator <, my program works. If I use the implementation inside the class, I get a compiler error. Why doesn't implementing this as a class member function work? Part of the error I get: usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_function.h:386:20: error: invali...
They should be overloaded with const directive. Otherwise, the non const operators can't be applied to const my whatever a.k.a. std::set<my>::key_type whatever inside std::set. Add bool operator> (const my& other) const { return this->a > other.a; } bool operator < (const my& other) const { return this->a < oth...
72,652,032
72,663,030
Attempting to do a T test with Rcpp using Boost: "No member named" errors
I am trying to make some statistical calculations in R faster by using Rcpp. First, I wrote the code in R. Then I wrote the code in C++ using Qt Creator, which required me to use the Boost package. Now, when I try to use sourceCpp() to compile a simple function that uses boost::math::statistics::two_sample_t_test(), I ...
There is a lot going on in your question, and I am not sure I understand all of (the 'design sorting' is very unclear). I can, however, help you with the mechanics of Rcpp, and use of Boost via BH. I can suggest a number of changes: you do not need to specify either C++11 or C++17; R already defaults to C++14 (if the ...
72,652,379
72,652,802
Which C++/Java graphics library does React Native use?
Since Flutter is using Skia for graphics, I was wondering what the equivalent for that would be for React Native. I managed to find an android.graphics.Canvas class in the React Native source code but that's about it. Finding it a bit harder to wrap my head around the React Native engine as opposed to the Flutter engin...
Contrary to Flutter, React Native doesn't render native UI elements on its own. View and Text, which are building blocks for React Native UI alter the corresponding OS UI elements, and rendering is handled by Native code via React Native Bridge. This architecture makes React Native not suitable for graphic-intensive a...
72,652,813
72,653,928
How to use extern for declaring/defining global variable in C++ and CUDA
I have the following code structure composed of one .cpp, one .cu and one .hxx UTILITIES.hxx #ifndef UTILITIES_HXX #define UTILITIES_HXX namespace B{ extern int doors; } FILE2.cu #include "utilities.hxx" namespace A { int foo (){ switch(B::doors){ //do something } } } FILE3.cxx #include "utilities.hxx...
missing #endif, missing return statement, no prototype for A::foo(), missing semicolon These changes seem to work for me: $ cat utilities.hxx #ifndef UTILITIES_HXX #define UTILITIES_HXX namespace B{ extern int doors; } #endif $ cat file2.h namespace A { int foo (); } $ cat file2.cu #include "utilities.hxx" namespa...
72,652,920
72,653,229
How to disable a wxTextCtrl Widget in wxWidgets C++?
I'm writing a wxWidgets program in C++. It has several single line wxTextCtrls in it and I need to disable them so the user cannot enter text in them. Later, when a menu item is clicked, I want to enable them again. How do I do this?
Since wxTextCtrl is a subclass of wxWindow, it contains (probably overridden) virtual method Enable of wxWindow, documentation for which can be found here and which controls whether the window is enabled for user input according to its boolean argument (which defaults to true - enable input). Also, there is a handy non...
72,653,144
72,653,228
OnRenderSizeChanged overriden with reduced access error?
I am hosting a Win32 OpenGL window in WPF through a DLL. In the DLL when I try to override OnRenderSizeChanged from the base class HwndHost I get the error that it is being overridden with reduced access. Why is this happening and how can I fix it? I am following these two tutorials Creating OpenGL Windows in WPF and W...
A class that implements a virtual method from a base class or any method from an interface cannot reduce the access of that method. Making the function public fixed it. public: virtual void OnRenderSizeChanged(SizeChangedInfo^ sizeInfo) override
72,653,257
72,668,698
How do I close this Gtk::MessageDialog before it's parent window is destructed?
I'm currently trying to create a simple Gtkmm program that has a button which spawns a dialog box. I'm currently having issues, however, as the destructor for the AppWindow class causes a segfault closing the dialog box. I check if the unique_ptr is nullptr before calling close, but even with that check it will crash i...
Suggestion in the comments is right, you should leave your destructor empty and not call dialog->close() there. To see why, note that this function is a wrapper for GTK C API function gtk_window_close, defined like this for Gtk::Window class (from which Gtk::MessageDialog inherits through Gtk::Dialog): // in gtk/gtkmm/...
72,653,259
72,653,434
How can I delete a self-defined node and let it be nullptr in the function
class node { public: node* next; int val; }; void func(node* root) { node* p=root->next; delete p; p=nullptr; } int main() { node* root=new node(); node* nxt=new node(); root->val=1;root->next=nxt; nxt->val=2;nxt->next=nullptr; func(root); cout<<(nxt==nullptr)<<end...
In func(), p is its own unique variable. In your example, it holds a copy of the address held in root->next. So, whatever you do to p itself, will not effect root->next in any way. However, when you are calling delete p, you are destroying the Node object that both p and root->next are pointing at. You are setting p...
72,653,519
72,664,662
Am I correctly rotating my model using matrices?
I have been getting unexpected behavior while trying to rotate a basic cube. It may be helpful to know that translating the cube works correctly in the y and z direction. However, translating along the x axis is backwards(I negate only x for proper results) which I haven't been able to figure out why. Furthermore, ro...
The unit of the angle of glm::rotate is radians. Use glm::radians to convert form degrees to radians: model = glm::rotate(model, 30.0f, rotation); model = glm::rotate(model, glm::radians(30.0f), rotation);
72,653,572
72,653,665
Argument of type "const wchar_t*" is incompatible with parameter of type "LPTSTR"
I am a programmer familiar with C# & Java and new to C++. I am trying to create an editor in C# WPF for my C++ OpenGL application and I am following these tutorials: Creating OpenGL Windows in WPF and Walkthrough: Host a Win32 Control in WPF. The latter is from Microsoft. This line of code Helper::ErrorExit(L"RegisterW...
TEXT("RegisterWindowClass") is supposed to be used. Avoid using L"RegisterWindowClass" or "RegisterWindowClass" with parameters of type LPTSTR. Also change the parameter type to LPCTSTR in static void ErrorExit(LPCTSTR lpszFunction).
72,654,201
72,654,260
What is the use case for not having lazy evaluation of value_or()?
I was having trouble when using foo.value_or(bar()) in my code, because I wasn't expecting the function bar() to be called when the optional variable foo had a value. I've since found this question that explains that value_or() doesn't use lazy evaluation. Now I'm left wondering why that is, when lazy evaluation has al...
It's not possible to design a function that does lazy evaluation. Function arguments are always evaluated if the function call itself is evaluated. The ONLY things that can short-circuit or evaluate in a lazy way are the built-in && and || and ?: operators. Other related comments: A few Standard library functions or fe...
72,654,323
72,656,297
Accessing parent window from a dialog in mfc
I am making a doc/view arch SDI application. I invoke a COptionsDialog in CSquaresView. void CSquaresView::OnOptions() { COptionsDialog dlg(this); if (dlg.DoModal() == IDOK) ... } In COptionsDialog I want to access CSquaresView. BOOL COptionsDialog::OnInitDialog() { CDialog::OnInitDialog(); CWnd *pParent = GetPa...
The observed behavior makes sense. A (modal) dialog's owner must be an overlapped or pop-up window [...]; a child window cannot be an owner window. CView-derived class instances generally are child windows. As such they cannot be the owner of a (modal) dialog. When you pass a child window into the c'tor of a CDialog-...
72,654,401
72,654,683
"A breakpoint instruction (__debugbreak() statement or a similar call) was executed in Main.exe", but there is no error?
I have an infinite loop that breaks if user exits out of the main window. I have the following code running in the loop: unsigned int* renderableShapeIndices = new unsigned int[aNumberCreatedAtRuntime]; // Do something delete[] renderableShapeIndices; Then the following happens a couple of loop iterations and cease to...
The answer to the problem is in the comment section of the question. Apparently, if one attempts to write to an array outside of its bounds, it will, but it ends up overwriting data of other places in the code, causing bugs in other parts of the program, even if these two parts of the program are unrelated. In my case,...
72,654,526
72,654,586
Calling the overriding function through a reference of base class
I googled and learnt the differences between function hiding and function overriding. I mean I understand the output of testStuff(), which is seen in the below code snippet. But what confuses me is that a instance of derived class could be assigned to a reference of the base class. And calling the overriding function t...
But what confuses me is that a instance of derived class could be assigned to a reference of the base class. And calling the overriding function through the said reference finally invoking the function of the derived class other than the base class. It is indeed exactly like that. If a member function is virtual in a...
72,654,693
72,654,744
Default constructed std::string c_str() value
std::string s1; std::string s2; assert(strlen(s1.c_str()) == 0); assert(s1.c_str() == s2.c_str()); Does these two assert always true? I use C++11, and I have checked the standard, the Table 63 in §21.4.2 says: data() a non-null pointer that is copyable and can have 0 added to it size() 0 capacity() an unspecified val...
The first assertion is guaranteed to succeed. c_str() always returns a pointer to a null-terminated string with the same string contents as held by the std::string object, which is an empty string for both s1. The second assertion is not guaranteed to succeed. There is nothing requiring the c_str() returned from a std:...
72,655,106
72,655,314
I'm getting a SIGSEV signal when running a program on HackerRank
I had made a post yesterday but I scrapped it and approached it with C++ instead of Java. I tested the code on the compiler installed on my computer and it ran fine. When I run it on HackerRank, it keeps giving me Segmentation fault. Please find the code and compiler output below. I read a few posts that mentioned it c...
The error is here if (flag ==1) d.push_back(dates[i]); It should be if (flag == 0) d.push_back(dates[i]); You got your logic wrong. You are trying to avoid adding duplicates to your vector but you ended up adding only duplicates which means that nothing gets added to the d vector. Then this line retur...
72,655,842
72,655,916
Area of Boost c++ in Square Meters
I have a boost::geometry::model::polygon<Point> Algorithm::poly and i'm looking for the area of the polygon with area = bg::area(poly); the result is 1.10434e+08 When i'm reading the documentation, i can see "The units are the square of the units used for the points defining the surface". I really don't understand w...
The points in polyare cartesian (x,y) coordinates. What is their unit? are they in mm, cm, attoparsec? The resulting unit is the square of that. But we can work that out from the data given: sqrt(1.1043e+08 / 11043) = srqt(10000) = 100 So it seems your points are in 0.01 m == centimeter, so the area returned is in cm²...
72,655,861
72,656,057
string returns xstring file location
#include <iostream> #include <conio.h> #include <stack> #include <string> using namespace std; int main{ string h = ""; h = ("" + 'a'); cout << h; return 0; } Output: "nity\VC\Tools\MSVC\14.29.30133\include\xstring" I am honestly clueless as to what to do. I've never had this happen before. Note: I'v...
"" is a literal of type const char[1], which is the identical as const char* in most regards. 'a' is a literal of type char, which is really just an integer type. So if you do "" + 'a', you will get a pointer to 'a' (=97 in ASCII) characters after wherever the compiler decides to put the "". Which is then converted to ...
72,656,102
72,657,951
OpenSSL BIO thread safety
OpenSSL's FAQ about thread safety says the following: Yes but with some limitations; for example, an SSL connection cannot be used concurrently by multiple threads. This is true for most OpenSSL objects. It does not allow me to understand whether the following will be safe: I call a blocking read on a BIO If my appl...
OpenSSL does not guarantee thread safety if you call 2 functions using the same BIO object at the same time from 2 different threads. However that is not what you are doing. You are sharing an fd between two different threads. One copy of the fd is being used by the OpenSSL library in the BIO_read() call in one thread,...
72,656,369
72,656,544
Overloaded operator= to switch between template types
I have a template class that multiple classes are inheriting from to basically make some user-friendly builders, hiding the functions that are not required on different builders, while following DRY. However, I'm having trouble switching between the builder types. I'd prefer to use the operator= to switch without hassl...
When you do the template inheritance, you have to be explicit in case of base classes members. More read: Why do I have to access template base class members through the this pointer? Derived template-class access to base-class member-data Accessing base member functions in class derived from template class In your c...
72,656,837
72,657,678
QT CPP login dialog cloisng when input wrong password
I made a simple login with qdialog on main.cpp file. When I input wrong password, Dialog didn't asks password again, simple closing a dialog. How can I make asks again when input wrong? QT 5.15 C++ Here is my code QString login = QInputDialog::getText(NULL, "Login","username",QLineEdit::Normal); if (login == cn...
This should work: QString login = QInputDialog::getText(NULL, "Login","username",QLineEdit::Normal); if (login == cnstnt::username) { QString getPassword = QInputDialog::getText(NULL, "Login","password",QLineEdit::Password); QString hashpassword = hlpr::passwordHash(getPassword.toUtf8()); while (hashpassword !...
72,656,838
72,656,982
no operator "/" matches these operands
trying to make player shoot 360 is there something wrong or misspelled? #include <SFML/Graphics.hpp> #include <SFML/Network.hpp> #include <SFML/System.hpp> #include <SFML/Window.hpp> using namespace sf; int main() { RenderWindow window(VideoMode(800, 600), "360 shooting object"); CircleShape circle(25.f); ...
Firstly your math is wrong aimDirectionNorm = aimDirection / sqrt(pow(aimDirection.x, 2)) + sqrt(pow(aimDirection.y, 2)); should be aimDirectionNorm = aimDirection / sqrt(pow(aimDirection.x, 2) + pow(aimDirection.y, 2)); Secondly operator/ requires a Vector2f and a float but sqrt returns a double. Because V...
72,656,879
72,657,888
Boost Spirit parser rule to parse square brackets
I have to parse a string that can optionally have square brackets in it. For e.g. This can be my token string: xyz[aa:bb]:blah I have used rules like +(~qi::char_("\r\n;,=")) +(~qi::char_("\r\n;,=") | "[" | "]") +(qi::char_ - qi::char_("\r\n;,=")) But none of them accepts the square brackets. Is there some special ha...
You need to show the code. Here's a simple tester that shows that all of the parsers succeed and give the expected result: Live On Coliru #include <boost/spirit/include/qi.hpp> #include <iomanip> namespace qi = boost::spirit::qi; int main() { using It = std::string::const_iterator; for(std::string const inpu...
72,657,632
72,657,725
Last node is not printed in Linked List
I was trying to learn the Linked list and perform insertion operations from beginning of the list. while printing the nodes, the first node is not printed. Here is the core functions which I have written. Can someone help me? struct Node //basic structure for a node { ll data; //data which we want to store Node...
Your Print function requires that the last node is linked or it won't be printed. Since the last node is never linked, it will never be printed. void Print() { Node* temp = head; while(temp) // <- corrected condition { std::cout << temp->data << ' '; temp = temp->link; } std::co...
72,657,973
72,658,442
Scope of dynamic (multidimm) array when initialized with pointer and new
I'm royally confused right now. I have seen similar questions asked, and my implementation seems to be along the lines of these solutions, but I just can't get it to work. I need to have a UtilClass that can initialize and dump a multi-dimensional dynamic array. I just want to pass the pointer the the array in BaseClas...
Let me start off with a piece of advice: it's best to reuse existing tools. Consider using std::vector for dynamically-allocated array. This is well tested, optimized and easy to use. Otherwise, you'll need to deal with conundrums of memory management (e.g. deallocate the allocated chunks of memory in the dtor of BaseC...
72,658,026
72,658,186
Clang and GCC disagree on whether overloaded function templates are ambiguous
I'm trying to port some code written for GCC (8.2) to be compilable by Clang: #include <tuple> struct Q{}; using TUP = std::tuple<Q>; template<typename Fn> inline void feh(Fn&, const std::tuple<>*) {} template<typename Fn, typename H> inline void feh(Fn& fn, const std::tuple<H>*) { fn(H{}); } template<typenam...
clang++ is correct because both functions matches equally good. I'm unsure which compiler that is correct, but... A C++11 solution could be to just add the requirement that the Rest part must contain at least one type and that is easily done by just adding R1. That would mean that the rest of your code could be left un...
72,658,358
72,658,579
Is it safe to grab the ownership of a STL vector's pointer?
I want to use the vector to collect some generated ints, the number of which I don't know until runtime. However, the interface I have to implement requires returning a native pointer which is supposed to be freed by the caller. The vector is going to be quite large, so, to avoid copying, I do the following: std::vecto...
You can, but not with std::vector<int>. You need an allocator that is compatible with the deallocation, and that will not deallocate the final array. If you new, new[] or malloc you must respectively delete, delete[] or free, mixing those is undefined behaviour. You must check how the interface deallocates the return v...
72,659,156
72,659,705
Convert double to integer mantissa and exponents
I am trying extract the mantissa and exponent part from the double. For the test data '0.15625', expected mantissa and exponent are '5' and '-5' respectively (5*2^-5). double value = 0.15625; double mantissa = frexp(value, &exp); Result: mantissa = 0.625 and exp = -2. Here the mantissa returned is a fraction. For my...
#include <cmath> // For frexp. #include <iomanip> // For fixed and setprecision. #include <iostream> // For cout. #include <limits> // For properties of floating-point format. int main(void) { double value = 0.15625; // Separate value into significand in [.5, 1) and exponent. i...
72,659,627
72,659,757
Template Error with passing member functions that contain a mutex
I spend an hour wiggling down a large class I needed to pass a member function of to a minimal example. The compiler error given is: error C2664: 'B::B(const B &)': cannot convert argument 1 from '_Ty' to 'const B &' Below is a minimal example and the Code compiles fine when using a pointer to the mutex. Can somebody...
A std::mutex is non-copyable, its copy constructor is deleted. There are no defined semantics for copying a mutex, what does that mean? If a mutex has locked something, does it mean that, somehow, two mutexes managed to lock the same object, the original and the copy, and both must be unlocked. For this reason a std::m...
72,660,072
72,663,972
How to get filename from __FILE__ and concat with __LINE__ at compile time
I'm trying to concat filename and line without path at compile time. Like /tmp/main.cpp20 -> main.cpp:20 #include <array> #include <iostream> using namespace std; #define STRINGIZE(x) STRINGIZE2(x) #define STRINGIZE2(x) #x #define LINE_STRING STRINGIZE(__LINE__) constexpr const char* file_name(const char* path) { ...
For your specific case (getting the filename without path and the line number) there are a few easier approaches that you might want to use: 1. Using __FILE_NAME__ instead of __FILE__ Both gcc and clang support the __FILE_NAME__ macro, that just resolves to the filename instead of the full file path. clang builtin ma...
72,660,983
72,661,891
Nearest Neigbor Search - Find which values are out of place based on position
I am currently working on a program in C++ which analyzes positions detected in the current frame compared to the last frame. In the case where one or more position is detected in the current frame, I need to estimate which objects are new. To do this, I can't simply find which values are the furthest from all other va...
One way of solving this would be to frame it as a minimum-weight bipartite matching problem. Specifically, you’re trying to pair off items in the old frame with items in the new frame in a way that minimizes the total distance between the matched points. There are many standard algorithms for solving this problem in a ...
72,661,534
72,661,632
Is throwing a temporary value as reference undefined behavior?
To my surprise, std::runtime_error only has a const std::string& constructor, but no value constructor. Thus I am wondering if throw std::runtime_error("Temporary" + std::to_string(100)); is defined. After all we are creating an exception object that refers to a temporary object inside the scope of a function that imme...
The const std::string& constructor doesn't cause the exception object to store a reference to the passed std::string. std::runtime_error will make an internal copy of the passed string (although the copy will be stored in an usual way, probably reference-counted in an allocation external to the exception object; this i...
72,661,625
72,661,795
Pybind11 - Function with unknown number of arguments
I want to get a list of arguments my current c++ code: m.def("test", [](std::vector<pybind11::object> args){ return ExecuteFunction("test", args); }); my current python code: module.test(["-2382.430176", "-610.183594", "12.673874"]) module.test([]) I want my python code to look like this: module.test("-2382.43017...
Such generic functions module.test(*args) can be created using pybind11: void test(py::args args) { // do something with arg } // Binding code m.def("test", &test); Or m.def("test", [](py::args args){ // do something with arg }); See Accepting *args and **kwargs and the example for more details.
72,661,799
72,661,937
Makefile only using the first entry of wildcard
I just got into Makefiles and I have a problem when turning the .cpp files in .o files. The list of files to be used are defined as the following: # Directories BIN_DIR = bin SRC_DIR = src ICD_DIR = include OBJ_DIR = $(BIN_DIR)/obj # Files SOURCES := $(wildcard $(SRC_DIR)/*.cpp) OBJECTS := $(SOURCES:$(SRC_DI...
I suggest that you create a pattern to build a single object file: $(BIN_DIR)/$(EXECUTABLE): $(OBJECTS) $(CXX) $(CXXFLAGS) -o $@ $(OBJECTS) bin/obj/%.o : src/%.cpp | $(OBJ_DIR) $(CXX) $(CXXFLAGS) -c $< -o $@ $(OBJ_DIR): mkdir -p $(OBJ_DIR) Since $(BIN_DIR)/$(EXECUTABLE) requires all object fi...
72,662,023
72,663,521
LoadString returns empty string
I want to store positions of some objects in resource file and I've decided to store it in STRINGTABLE resource, because I couldn't find better type. My resource file: #include "resource.h" // POSITIONS_ID = 10 defined in resource.h STRINGTABLE { POSITIONS_ID "100 100 \ 200 350 \ 400 800" } I've tried to get this stri...
In "resource.h" file I defined POSITIONS_ID this way #define POSTIONS_ID 0010 to make defines look better, but for some reason leading zeros mustn't be used in resource ids. Also I've find out, that when I use FindResource with type RT_STRING, I am looking for STRINGTABLE resource, that contains up to 16 string, so I h...
72,662,468
72,666,184
Outside of using volatile, how can I assure that I'm querying the latest value from memory?
I understand that the compiler may choose to hold a value in cache, and that I can ensure that it reads the latest value from memory every time by using volatile, but are there other ways I can ensure that the latest value is being read without adding a type qualifier?
Outside of using volatile, how can I assure that I'm querying the latest value from memory? You can't be assured that you're actually accessing memory, at least not in a portable way. Even if you use std::atomic or atomic variables (e.g. atomic_int in C) there is no guarantee that the value will come from to memory a...
72,662,728
73,032,981
How to manipulate images in SFML?
I need to implement a class (inherited from sf::Image) that allows me to find 'distance' between two images. By that I mean a measure of how the images differ from each other pixel by pixel (the specifics don't matter). The main idea is to take an image, draw something on it and look at how much it changed. To draw som...
You really shouldn't derive from sf::Image (see also Composition over Inheritance). To go from a sf::RenderTexture to an sf::Image you can use renderTexture.getTexture().copyToImage(), but keep in mind that requires transferring of data from the GPU's VRAM to the CPU's RAM and as such it can be rather slow, meaning you...
72,663,001
72,663,085
Why does this example involving std::accumulate compile (badly), and how to guard against misuse?
Surprinsingly (for me), this compiles: std::vector<int> v; std::accumulate(std::cbegin(v), std::cend(v), 0, [](double sum, auto i){ return sum + 0.1; }); (gcc 12 with --std=c++20a) This is bad, because if I look at the signature of std::accumulate, it returns what's passed in the init argument, whi...
This is the defined behavior of std::accumulate. It will initialize the accumulator with the initial value provided and take on its type. Then it will repeatedly add new values with the accumulator, always assigning the intermediate results to the accumulator object. The assignment coerces the double result of the lamb...
72,663,242
72,663,288
C++ ofstream write in file from input, without new line after each word
Basically I have a function, that writes into a .txt file. The user has to input, what will be written in the file. The problem is, every word has a new line, even tho it's written in the same line, while doing the input. But I want it to be the way the user inputs it. void Log_Write::WriteInLog(std::string LogFile...
std::cin >> input; just reads to the first whitespace while std::getline(std::cin, input); would read the whole line. One way of fixing it: while( system("cls"), std::cout << "Writing in Log\n\nType 'x' to leave editor!\n\nInsert new entry: ", std::getline(std::cin, input) ) { if (input == "x") ...
72,663,249
72,663,990
find out if cursor had been set in ncurses.h
I'm creating a wrapper for menu.h and want to ensure that when a menu is displayed, the cursor is turned off, however I don't want to just do a curs_set(0); and potentially screw up some other ui that depends on a certain cursor setting... TLDR: is there any way to find out the current setting of curs_set?
It's in the manual page: The curs_set routine sets the cursor state to invisible, normal, or very visible for visibility equal to 0, 1, or 2 respectively. If the terminal supports the visibility requested, the previous cursor state is returned; otherwise, ERR is returned.
72,663,370
72,664,851
Allow Only Explicit Specialization of Template Class
I want to limit a template class to the only explicit implementations. I can do this with many functions as: template<typename T> static T getEnumFromString(const std::string& in_string) = delete; // only allow templates we define (catches them at compile time) template<> static A getEnumFromString(const std::string& i...
There are a few ways how you could accomplish this. 1. Explicitly list the acceptable enums One way would be to explicitly list the acceptable enums in your static_assert: godbolt #include <type_traits> template<class T, class... Other> constexpr bool is_same_one_of = (std::is_same_v<T, Other> || ...); enum Enum1 {};...
72,664,029
72,664,101
MSVC vs Clang/GCC bug during overload resolution of function templates one of which contains a parameter pack
I was using parameter pack when I noticed that one such case(shown below) compiles fine in gcc and clang but not in msvc: template<class T> void func(T a, T b= T{}) { } template<class T, class... S> void func(T a, S... b) { } int main() { func(1); // Should this call succeed? } Here is the link for verify...
MSVC is right in rejecting the code. According to temp.func.order#5.example-2 the call func(1) is ambiguous. The example given in the standard is as follows: Note: Since, in a call context, such type deduction considers only parameters for which there are explicit call arguments, some parameters are ignored (namely, f...
72,664,301
72,664,686
How to make Tensorflow-lite available for the entire system in Ubuntu
My tflite directory is as follows: /home/me/tensorflow_src/tensorflow/lite/ However, I fail to import it in my C++ project: #include "tensorflow/lite/interpreter.h" // getting a not found error How can I add resolve this error? My assumption is that I'd need to add the tflite to my bash to make it available for all o...
There are various options: First option: Install/copy the tensorflow header files to e.g. /urs/local/include that folder is usually in the system include path by default. Second option: GCC has some environment variables that can be used to modify the system include path. C_INCLUDE_PATH and CPLUS_INCLUDE_PATH, your can...
72,665,022
72,665,125
Lib SDL C++ Why wont my app compile with -static and libc
I am trying to learn how to use SDL and I've been trying to get my app to run on other systems. when I try to compile using g++ -I src/include -L src/lib -o main main.cpp -lmingw32 -lSDL2main -lSDL2 -static-libgcc -static-libstdc++ -static I get a massive bunch of SDL errors saying undefined and the app doesn't finish ...
You're missing some flags. Running pkg-config --libs --static sdl2 will tell you the right flags. If you don't have pkg-config installed (you could get it from MSYS2), you can look up the flags manually in the file called sdl2.pc, which is shipped with SDL2. For me this command prints -L/mingw64/lib -lSDL2main -lmingw3...
72,665,285
72,665,331
Nested Classes with Template
I'm having issues using a nested class with a template. The first snippet is provided, I just have to implement it. template <typename T> class a { public: class b { public: func(); I thought the implementation would look something like this, but it isn't working. template<typename ...
There's not much wrong with your start. You just need to to tie it together. template <typename T> class a { public: class b { public: void func(); // return type missing }; // missing }; // missing template <typename T> void a<T>::b ::func() {} // ^ not <T> Demo
72,665,491
72,692,573
How to convert for loop matrix multiplication using Eigen C++: incorrect results
I have the following for loop that works: static const int ny = 10; std::vector<double> ygl(ny+1); double *dVGL; dVGL = (double*) fftw_malloc(((ny+1)*(ny+1))*sizeof(double)); memset(dVGL, 42, ((ny+1)*(ny+1))* sizeof(double)); double *dummy1; dummy1 = (double*) fftw_malloc(((ny+1)*(ny+1))...
Thanks to @chtz in the comments, I was able to fix this problem simply by changing my indexing: dVGL(j + (ny+1)*i) = sin(acos(ygl[j]) * (i)); dv1 = (dummy1) * (dVGL) * (dummy2); //Then this is correct
72,665,745
72,666,095
vkCreateRenderPass returns invalid pointer
I am creating a render pass like so const bool createRenderPass() { VkAttachmentDescription colorAttachment{}; colorAttachment.format = swapChainImageFormat; colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT; colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE...
However when I run it renderPass results in an invalid pointer: 0xe000000000e There are two types of handle returned by Vulkan functions: dispatchable: Dispatchable handle types are a pointer to an opaque type. This pointer may be used by layers as part of intercepting API commands, and thus each API command takes...
72,665,889
72,665,921
Is it possible to initialize a enumeration data member inside constructor?
I have 2 questions Is enumeration constant of int datatype? For class Card, do I create two data member of enum type Face and Suit and then initialize it via the constructor? Background: 9.23 (Card Shuffling and Dealing) Create a program to shuffle and deal a deck of cards. The program should consist of class Card, c...
An enumeration constant presumably is of an enum type: https://en.cppreference.com/w/cpp/language/enum . Yes, depending on the kind enumeration, it can be converted to integers, sometimes the conversion makes sense (e.g. for the face value) but in some cases you want to stay away from it (e.g. for the suit value). For ...
72,665,933
72,666,564
Find size of glm::vec3 array
I have this glm::vec3 array and I would like to know the size of the array: glm::vec3 cubePositions[] = { glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::ve...
cubePositions is a C style array. It decays to a pointer to glm::vec3. See here about array to pointer decay: What is array to pointer decay?. Therefore when you use cubePositions->length() it's equivalent to using cubePositions[0].length(), which returns the glm length of the first element (i.e. 3 because it's a vec3)...
72,666,452
72,666,606
Why doesn't memory blow up for an infinite pointer chain in C++?
Beginner question: In relation to this original question here, every variable we generate has a memory address to it, and the pointer holds that memory address. The pointer itself also has its own memory address. Why doesn't this recursively generate an infinite chain of memory-addresses that hold other memory-addresse...
What am I missing here? The names of the pointers. An expression like &(&a) is not valid; there needs to be a name for an address before you can take the address again. (There are more precise ways to express that, but the more precise ways can also be more confusing at this stage.) In the linked-to question, there i...
72,666,655
72,666,679
Why when i add \ to cout it dosent display it on output
When I try to do printf("----/");, the \ is removed from the output #include <iostream> int main() { std::cout << ("Welcome to the game\n\n"); printf("--------\n"); printf("----O---\n"); printf("---/|\--\n"); printf("---/-\--\n"); } output: -------- ----0--- ---/|-- ---/---
The answer has been given already: \ is special, because it's the escape character, and you need to escape it with itself if you want a literal \ in the outoupt. This, however, can make the drawing confused. To improve the things, you can use raw strings literals printf(R"(-------- ----O--- ---/|\-- ---/-\--)"); N...
72,667,067
72,667,190
The "sticks" variable cannot be re-assigned to 0 in C++14
I am writing a program to resolve the request: Count the number of match sticks used to create numbers in each test case Although it is a simple problem, the thing that makes me quite confusing is that the program has no error but the output is not as expected. Source Code: #include <bits/stdc++.h> using namespace s...
There are 3 problems with your code don't use <bits/stdc++.h>, it is non-standard and promotes bad practice. variable-length arrays are not standard C++, use std::vector instead. But this is actually not necessary in this case, because... peterMap is completely unnecessary and needs to be removed, it is screwing up...
72,667,689
72,668,526
How to understand the type returned by the final overrider is implicitly converted to the return type of the overridden function that was called?
As per the document, which says that[emphasis mine]: When a virtual function call is made, the type returned by the final overrider is implicitly converted to the return type of the overridden function that was called. How to understand that in the right way? According to the output of the demo code below, it seems t...
the return type of the overridden function that was called. Note the word choice. The function that was called, not the function that was executed. Your examples focus on executing the same function. The function that was called depends on how you place the call (compile time), not how the call is answered (run time)...
72,667,852
72,668,060
Why does my concept not work if specifying two requirements
I have the following code: #include <concepts> #include <functional> #include <iostream> template<typename T> concept OperatorLike = requires(T t, const std::string s) { { t.get_string(s) } -> std::same_as<const std::string>; { t.get_int(s) } -> std::same_as<const int>; }; template<typename T, typename O> co...
The compound requirement { t.get_int(s) } -> std::same_as<const int>; tests whether decltype((t.get_int(s))) is the same as const int. However, that is a pointless test, because there are no const prvalues of non-class type and these would be the only expressions for which decltype could result in const int. A prvalue...
72,668,066
72,668,075
mktime returns -1 but valid data
I try to find a way for a default date (if date is not valid). Common way works fine: set(2022,6,17,12,12,0,0,0) void KTime::Set(int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec, int nDST, bool isUTC) { assert(nYear >= 1900); assert(nMonth >= 1 && nMonth <= 12); assert(nDay >= 1 && nDay <= 31...
mktime (and the rest of the POSIX date functions) only work for dates >= 1970-01-01 00:00:00, the UNIX epoch. mktime, quoth the manual, returns -1 if time cannot be represented as a time_t object and 1900 definitely can't be represented as a time_t, since it's 70 years early.
72,668,467
72,668,583
Transform variadic type list to tuple of pairs
Is the following type transformation possible: T1, T2, T3, T4, ...., T2n-1, T2n ---> transform to ---> tuple< pair<T1, T2>, pair<T3, T4>, ..., pair<T2n-1, T2n> > Such a meta-function template <class... Args> using split_in_pairs_t = ??? would be used like so: template <class... Args> class UseCase { ...
Make an index sequence of half the size, and pair elements 2*i, 2*i+1 together: template <class...> struct pairwise_impl; template <class... Args, size_t... Is> struct pairwise_impl<std::tuple<Args...>, std::index_sequence<Is...>> { using full_tuple_t = std::tuple<Args...>; using type = std::tuple<std::p...
72,668,474
72,668,531
How change the second letter in char *name = "exemple"; with char *name
I am studying c++ to get a good understanding of memory. char *name = "example"; *(&name+1) = (char*)'A'; std::cout << name << std::endl; is returning example not eAample. My idea is to get the memory address of 'x' and changed it. Is not a const so I should be able to change the value of the address right? obs: I ...
This declaration char *name = "example"; is invalid. In C++ string literals have types of constant character arrays. It means that you have to write const char *name = "example"; and you may not change the string literal. Even in C where string literals have types of non-constant character arrays you may not change a...
72,668,537
72,668,799
PushButton is opened in different window
i am new at QT i created a window and i want to add a button on this window but the button is opened in different window. How to add this button to default window Here is my code; mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" #include "QPushButton" #include "QDesktopWidget" #include <iostream> usin...
You need to make QPushButton a child of the main window for it to be rendered inside the main window, otherwise QPushButton will be an independent widget. Usually all Qt Widgets accept a pointer to parent widget, QPushButton also accept a pointer to parent widtet. QPushButton(const QString &text, QWidget *parent = null...
72,669,120
72,671,083
CMake isn't able to include header file into my source file
I'm learning CMake and got to the part where I learn how to include header files. The problem is that I get an error, saying that the header file has not been found. I'm on Windows 10, by the way. All I have as of right now is a src and include directories along with the CMakeLists.txt file. In source, I only have a si...
It's ${CMAKE_CURRENT_SOURCE_DIR}, not ${CMAKE_CURRENT_SRC_DIR}. If you fix this then the compiler should see the correct include directory. At the moment because the variable doesn't exist, the only directory it sees is /include which is not what you want.
72,669,278
72,669,308
Coding own shell, error "exec: bad adress"
I'm trying to code my own shell in c++ and have stumbled upon an error, I don't know how to fix. You have to type in a command in the terminal, most of them work as well, but if I try to include more than one argument or spaces between letters (example: echo 1 2 3) the shell says "exec: bad adress". I'm coding the shel...
char* args[argsBefore.size()]; for(size_t i =0; i<=(argsBefore.size());i++){ args[i]=(char*)argsBefore[i].c_str(); } args[sizeof(args)+1]=NULL; Firstly char* args[argsBefore.size()]; is not legal C++ (but g++ will accept it). In C++ array sizes must be compile time constants. More importantly ...
72,669,579
72,669,632
C++ how to set environment variable so OpenBLAS runs multithreaded
The author recommends the following: https://github.com/xianyi/OpenBLAS Setting the number of threads using environment variables Environment variables are used to specify a maximum number of threads. For example, export OPENBLAS_NUM_THREADS=4 export GOTO_NUM_THREADS=4 export OMP_NUM_THREADS=4 The priorities are OPE...
When I use "export OPENBLAS_NUM_THREADS=16" in my main.cpp, I get an error about templates. OPENBLAS_NUM_THREADS is a runtime defined variable so it should not impact the build of an application unless the build scripts explicitly use this variable which is very unusual and a very bad idea (since the compile-time env...
72,670,090
72,670,195
Is shared_ptr::unique() indicative that only one thread owns it?
I have a worker thread giving my rendering thread a std::shared_ptr<Bitmap> as part of how I download texture data from the GPU. Both threads depend on std::shared_ptr<...>::unique() to determine if the other thread is done with the Bitmap. No other copies of this shared pointer are in play. Here's a trimmed down cha...
No, it is not safe. A call to unique (or to use_count) does not imply any synchronization. If e.g. the worker thread observes bitmap.unique() as true, this does not imply any memory ordering on the accesses made by fillBitmap(*it); and those made by bitmap->saveToDisk();. The function call may be implemented as a relax...
72,670,521
72,670,946
Is openmp included in stdio.h in c/c++?
I searched about openmp, and realised that some people includes omp.h and others do not. They just include stdio.h. So my question is: Is openmp included in stdio.h so that we can use opemp if we only include it? I think old openmp such as openmp2.0 need to be used with omp.h but openmp3.0 does not need to be so. but I...
stdio.h does not contain omp.h. Your confusion may be because to use #pragma omp ... directives you do not have to include omp.h, so it means that you can write an OpenMP program without including omp.h. On the other hand, if you use any OpenMP runtime library function (e.g. omp_get_num_threads()) you have to include o...
72,670,631
72,671,926
openGL doesen't let me draw in a class
I am trying to create a text class witch has its own vertex array, vertex buffer, index buffer and draw them on a function call. It looks like so: class Text { private: std::string m_FontFilePath; std::string m_Text; Texture* m_FontTexture; VertexBuffer* m_Vbo; IndexBuffer* m_Ibo; VertexArray* ...
Your buffers objects are local in scope of Text::Text. The attributes are dangling pointers. You have to create dynamic objects. Remove the local variables va2, vb2 and ibo2 but allocate dynamic memory and create the objects with the new operator: Text::Text(std::string fontFilePath, std::string text, float posX, float...
72,670,928
72,755,029
Type punning between `pair<Key, Value>` and `pair<const Key, Value>`
A relative question, but I want a solution without any run-time overhead. (So constructing a new pair or using std::variant are not the answers) Due to the potential template specialization, reference has said pair<K, V> and pair<const K, V> are not similar, that means a simple reinterpret_cast would trigger undefined...
This is impossible. The node_handle proposal mentioned this as a motivation for standardizing it: One of the reasons the Standard Library exists is to write non-portable and magical code that the client can’t write in portable C++ (e.g. , , <type_traits>, etc.). This is just another such example. Note that the key m...
72,670,980
72,671,682
Call the notify_all method after store with release memory order on an atomic
I have the following code being executed on a single thread (written in C++20): std::atomic_bool is_ready{}; void SetReady() { is_ready.store(true, std::memory_order_release); is_ready.notify_all(); } Other threads execute the text listed below: void Wait() { is_ready.wait(false, std::memory_order_acquire); } ...
The memory orders are irrelevant here. They only affect ordering of memory access other than on the atomic itself and you have none. The compiler cannot reorder the notify_all call before the store in any case, because notify_all is specified to wake up all waiting operations on the atomic which are eligible to be unbl...
72,671,139
72,677,166
Exclude points in overlapping area of two circles in OpenGL
I want to draw tow circles with the same radii but exclude the overlapped area when drawing. I want to draw or set dots on gray area. I implement the mathematical aspect behind it and here is my code: void draw_venn(){ float radian_to_degree_theta=2 * 3.14 / 360, r = 0.5, distance=0.3, ...
I reviewed and tested out your code. Trigonometry can get a bit tricky. Following is the "draw_venn" function with some refinements to produce an overlap effect. void draw_venn() { float radian_to_degree_theta=2 * 3.141 / 360, r = 0.5, distance=0.3, theta=0.0, ...
72,671,541
72,671,778
exploiting canary to buffer overflow in C
#include <cstdio> #include <cstring> #include <cstdlib> #include <stdint.h> #include <unistd.h> #include <time.h> #include <random> using namespace std; void login1(char * input1, char * input2) { struct { char username[20]; int canary; char password[20]; char good_username[20]; char good_password[...
In struct { char username[20]; int canary; char password[20];// a 60 char password can overwrite the next two members char good_username[20]; char good_password[20]; int goodcanary; // without touching this canary } The second canary is after the input password as well as the good user name and...
72,671,616
72,672,074
Remove out excess spaces from string in C++
I have written program for removing excess spaces from string. #include <iostream> #include <string> void RemoveExcessSpaces(std::string &s) { for (int i = 0; i < s.length(); i++) { while (s[i] == ' ')s.erase(s.begin() + i); while (s[i] != ' ' && i < s.length())i++; } if (s[s.length() - 1] == ' ')s.pop_ba...
That is because when your last while loop finds the space between your characters (this is) control pass to increment part of your for loop which will increase the value of int i then it will point to next character of given string that is i(this is string) that's why there is space between (this is).
72,671,703
72,671,868
Weight choices based on the most common number in an array
I'm trying to find out how to calculate the 'weight choices' based on the most frequent number in an array for AI to choose a particular number. For instance, I have this function which calculates the most common number in an array and allows the AI to choose a particular option to make the player lose. As it stands no...
This looks like the perfect place for a std::discrete_distribution. Walkthrough: #include <algorithm> #include <iostream> #include <map> #include <random> #include <vector> // A seeded pseudo random number generator: static std::mt19937 gen(std::random_device{}()); int main() { Say you have all the player choices in...
72,671,742
72,671,991
Why is this function call didn't reject the unsuitable overload?
Consider the following code: #include<vector> #include<ranges> #include<algorithm> //using namespace std; using namespace std::ranges; int main() { std::vector<int> a = {}; sort(a); return 0; } It's running properly. Obviously, it called this overload function(functor, strictly speaking): template<random_a...
The problem is that std::ranges::sort is implemented as function object and not a function. From name lookup rules: For function and function template names, name lookup can associate multiple declarations with the same name, and may obtain additional declarations from argument-dependent lookup. [...] For all other na...
72,671,882
72,672,265
How to build and run OpenSubdiv Tutorials/examples
I'm trying to experiment with the OpenSubdiv C++ library. I'm not an experienced C++ programmer. The OpenSubdiv library has some tutorials that I'd like to get working, but I can't figure out how. So far, I have installed OpenSubD and dependencies (GLFW) to the best of my extremely limited abilities, by doing the follo...
Please refer to the last section of OpenSubDiv: building with cmake. The linker needs to know where to find the library to link. Set the OPENSUBDIV variable to the directory of OpenSubDiv, then compile and link your app. g++ -I$OPENSUBDIV/include -c myapp.cpp g++ myapp.o -L$OPENSUBDIV/lib -losdGPU -losdCPU -o myapp
72,672,694
72,682,511
Eigen replace first row in matrix error: mismatched types ‘const Eigen::ArrayBase<ExponentDerived>’ and ‘int’
Trying to replace the first row of a matrix with some expression, similar to my MATLAB code: %Matrix A defined and Ny A(1,:) = (-1).^(1:Ny+1).*(0:Ny).^2; A(Ny+1,:) = (0:Ny).^2; The C++ code I wrote is: static const int ny = 10; Eigen::VectorXd i = VectorXd(ny+1); std::iota(i.begin(), i.end(), 0); /...
This is how I fixed the problem with help from @Sedenion in the comments: Eigen::ArrayXi exponents((ny+1)); exponents = Eigen::ArrayXi::LinSpaced((ny+1), 0, (ny+1)); A.row(0) = -1. * (Eigen::pow(-1., exponents.cast<double>())) * (Eigen::pow(exponents.cast<double>(),2)) ; //first row A.row((ny)) = 1. * (Eigen::pow(ex...
72,672,723
72,673,061
What is the fastest way to see if the values from a 2 dimensional array are present in 3 other two dimensional arrays
I have 4 integer two dimensional arrays of the form: {{1,2,3},{1,2,3},{1,2,3}} The first 3(A,B,C) are of size/shape [1000][3] and the 4th(D) [57100][3]. The combination of integers in the 3 elements sub-arrays in A,B,C are all unique, while combinations of integers in the 3 elements sub-arrays in D are not. What I have...
As suggested by my comments, let's assume your approach is a naive, look at one item at a time in a for loop to see if a match is found. Instead of doing that, another approach is to store the arrays as a std::set<std::tuple<int, int, int>> and do a lookup on the sets. Doing this reduces the time complexity from linea...
72,672,761
72,672,802
C++ Pass a string as a value or const string&
Say I have such simple functions: struct Data { string name; string value; // Can be very long }; // Use Data directly to avoid copy. (Not Data*) unordered_map<size_t, Data> g_data; // Should I use "const string& name, const string& value"? void addData(string name, string value) { // Should I use any std::move...
Yes, you should use std::move, but not like this. The proposed piece of code would try to hash moved-from strings (pre-C++17 it was unspecified if the strings would be already moved from at that point, see rule #20 here). You should pre-calculate the hash and store it in a variable: auto h = hash(name, value); g_data[h...
72,672,775
72,674,201
can't open file using c++
I am using linux g++ compiler and also visual studio code to compile and run the code below and each time I run it, it returns with could't open file. i have put the text file in the same folder as the c++ program but still to no avail. Can anyone point out where I have gone wrong? The code: #include <iostream> #includ...
Make sure that you have given the filename to the program as an argument. After being compiled by g++, you should run the program like this: ./program filename.txt argv[1] is the first program argument, in this case "filename.txt". Make sure that whatever launches the program is in the same working directory Make s...
72,673,067
72,679,309
Running parameterized queries in QSqlTableModel
I have a QTableView and I am using a derived class SqlTableModel of QSqlTableModel to fetch data from a MySQL database. I want to prevent injection. I ran a union injection and it was easier than taking candy from a baby. The SQL query utilizes the LIKE keyword. Attempt 1 (injectable): QString query = QString("select *...
It looks like you are using QSqlTableModel in wrong way. The common usage is to setTable with subsequent select call, according to docs model->setTable("table"); model->select() Filter can be set using setFilter model->setFilter(QString("col like '%%1%'").arg(edit->text())); Meanwhile you use a QSqlTableModel like it...
72,673,531
72,673,605
How to separate strings into 2D vector?
This is the file with data that I'm reading from: MATH201,Discrete Mathematics CSCI300,Introduction to Algorithms,CSCI200,MATH201 CSCI350,Operating Systems,CSCI300 CSCI101,Introduction to Programming in C++,CSCI100 CSCI100,Introduction to Computer Science CSCI301,Advanced Programming in C++,CSCI101 CSCI400,Large Softwa...
getline(.., .., ',') is the tool for the job, but you need to use it in a different place. Replace while (split >> value) with while (getline(split, value, ',').
72,673,535
72,683,207
Will built-in `operator->` be used if I don't overload it?
The builtin operator-> is defined as (*p).m, which is just fine for my iterator, so overloading it would just waste my time and the maintainer's eyes. Just trying it wouldn't guarantee portability, and I haven't been able to find an answer, though I fear that it is no, because apparently nobody has even considered it b...
Will built-in operator-> be used if I don't overload it? No, only certain special member functions are implicitly declared for a given class-type(and that too under certain circumstances). And operator-> is not one of them. This can be seen from special members which states: The six special members functions describ...
72,673,802
72,673,819
Inserting elements to vector in c++
I need to insert for every element of vector it's opposite. #include <iostream> #include <vector> int main() { std::vector < int > vek {1,2,3}; std::cout << vek[0] << " " << vek[1] << " " << vek[2] << std::endl; for (int i = 0; i < 3; i++) { std::cout << i << " " << vek[i] << std::endl; vek.insert(vek.beg...
During the for loop, you are modifying the vector: After the first iteration which inserts -1, the vector becomes [1, -1, 2, 3]. Therefore, vec[1] becomes -1 rather than 2. The index of 2 becomes 2. And after inserting -2 into the vector, the index of the original value 3 becomes 4. In the for loop condition, you need ...
72,673,837
72,674,114
C++11: how to use lambda as type parameter, where it requires a "functor type" like std::less/std::greater?
I'm trying to pass a type parameter to priority_queue, just like std::less or std::greater, like this: priority_queue<int, vector<int>, [](int x, int y){return x>y;})> q; It doesn't compile, then I added decltype, still fails: priority_queue<int, vector<int>, decltype([](int x, int y){return x>y;}))> q; Question is, ...
There are multiple ways: Let the compiler deduce the type of lamabda by using decltype(lambda). But one thing you need to keep in mind: Prior to C++20, lambda type does not have a default constructor. As of C++20, ONLY stateless lambda (lambda without captures) has a default constructor, while stateful lambda (i.e., l...
72,673,961
72,674,021
Visual Studio Code - C/C++ Extension commands don't exist
I've been using WSL2 with the C/C++ Extension on Visual Studio Code for quite a while now, but recently, it stopped working. Whenever I try to run a command, such as Edit Configurations, this error pops up: Text version: Command 'C/C++: Edit Configurations (UI)' resulted in an error (command 'C_Cpp.ConfigurationEditU...
This is an issue because clangd and intellisense do not work together. If you disabled intellisense in favor of clangd then the c/c++ configuration json/ui commands will not work. Instead of the configuration for the c/c++ extension you must generate a compile_commands.json for clangd using CMAKE. The fix that worked f...
72,673,966
72,673,976
Using data from 2D vector at runtime in C++
I have a function that takes the arguments of a 2D vector and writes the information from a file to that vector. But after I call the function and the data has been written to the vector, it acts as if the vector is empty, despite the vector being a accessible from anywhere in main. If do the printing within the load...
void LoadFile(vector<vector<string>> courseInfo) { ... } This creates a copy of the vector because you pass it by value. You then store all the data in the copy and at the end of the function the copy is destroyed. At no point do you modify the original vector. Change it to void LoadFile(vector<vector<string>> &course...
72,674,069
72,678,218
How can a WOW64 program overwrite its command-line arguments, as seen by WMI?
I'm trying to write a program that can mask its command line arguments after it reads them. I know this is stored in the PEB, so I tried using the answer to "How to get the Process Environment Block (PEB) address using assembler (x64 OS)?" by Sirmabus to get that and modify it there. Here's a minimal program that does ...
wow64 processes have 2 PEB (32 and 64 bit) and 2 different ProcessEnvironmentBlock (again 32 and 64). the command line exist in both. some tools take command line correct (from 32 ProcessEnvironmentBlock for 32bit processes) and some unconditional from 64bit ProcessEnvironmentBlock (on 64 bit os). so you want zero (all...
72,674,071
72,674,795
Visual Studio C++ How to Specify Relative Resource Path For Final Build
I already know how to set a relative working directory path and access resources inside of visual studio. However, when I build my solution and move the exe to a separate file I have to include all the resources in the same directory as the exe. I'd prefer to have a folder with said resources alongside the exe to keep ...
For a Windows solution, GetModuleFileName to find the exact path of your EXE. Then a simple string manipulation to make a resource path string. When you program starts, you can use this to ascertain the full path of your EXE. std::string pathToExe(MAX_PATH, '\0'); GetModuleFileName(nullptr, szPathToExe.data(), MAX_PATH...
72,674,420
72,674,511
How do I properly derive from a nested struct?
I have an abstract (templated) class that I want to have its own return type InferenceData. template <typename StateType> class Model { public: struct InferenceData; virtual InferenceData inference () = 0; }; Now below is an attempt to derive from it template <typename StateType> class MonteCarlo : public Mode...
You cannot change the return type of a derived virtual method. This is why your compilation failed when you try to return your derived InferenceData from MonteCarlo::inference(). In order to achieve what you need, you need to use a polymorphic return type, which requires pointer/reference semantics. For this your deriv...
72,674,454
72,674,670
LineTo() draw line in wrong place
I want to add a line to my text in notepad when printing a pdf, for these purpose I hook Enddoc function and use GDILineTo(). but when I print my text, the LineTo()creates new page at the end of pdf and draws Line in it. does any body knows how can I draw line in all pdf pages without create new page ? here is my code:...
I've no idea if this will work or quite what you're up to, but I think you need to 'hook' EndPage rather than EndDoc. Also, your hook function is broken in various ways so try this: int StopPrint::EndPageHook(HDC hdc) { HPEN holdPen = (HPEN) SelectObject(hdc, GetStockObject (BLACK_PEN)); POINT old_pos; Mov...
72,674,526
72,674,608
c++ std::map compare function leads to runtime "bad_function_call"
I'm declaring my std::map and use it below: map<int, int, function<bool (int, int)>> m; m.insert(make_pair(12,3)); m.insert(make_pair(3,4)); for(auto & p : m){ cout << p.first << "," << p.second << endl; } g++ compiles, no error. Template parameter only requires a type, but no function body...
The problem is not related to the template argument, but that you did not provide an actual value for it when constructing the map. Note that in the documentation for the map constructor, there is a const Compare& parameter. It is via this parameter that you must give a value for your comparator which in this case is a...
72,674,869
72,674,894
C++ pure virtual function call doesn't throw run-time exception?
It's said that in C++ constructor function, as long as the object has not finished construction, shouldn't call virtual function, or else there'll be "pure virtual function call error" thrown out. So I tried this: #include<stdio.h> class A{ virtual void f() = 0; }; class A1 : public A{ public: void f(){printf(...
You are not getting the "pure virtual method call" exception because A::f() is not being called. A1's constructor is calling its own A1::f() method, which is perfectly safe to do during A1's construction. The issue with calling a virtual method in a constructor has to do with a base class constructor calling a derived ...
72,676,233
72,676,311
loop as long an user input is given
I don't know how to write correct condition in my while loop. I want my program to loop as long as user will give an input value. So user gives values, program prints result and asks the same thing again. When user does not give any input and just presses enter i want my program to finish. Here is my code: #include <io...
You are asking for line based input, you said When user does not give any input and just presses enter i want my program to finish. But the input method you are using cin >> symbol; skips all spaces and newlines. So it cannot meet your requirements. Since you want to read lines of input you should use something that do...
72,676,527
72,676,660
Failed to show `` (UTF-16 character) in wxWidgets (C++)
I am using wxWidgets with Visual Studio 2022 (C++) to develop Windows application. I wish to display in the window, but as I tried using various fonts with the following code: std::string fonts_name[8] = {"Calibri Light", "Calibri", "Cambria Math", "Cambria", "Candara Light", "Candara", "Consolas", "DFKai-SB"}; // ......
As shown in the wxWidget's documentation, the correct way would be as shown below: //---------------------------------------vvvvvvvvv---->changed to u instead of x label = new wxStaticText(this, wxID_ANY, L"\u0078"); or label = new wxStaticText(this, wxID_ANY, L"\U0001D465");
72,677,645
72,677,698
When and how should I use std::predicate
I am trying to constrain a Callable to return a boolean when evaluated. I have been trying to use the concept std::predicate, but it does not seem to do what I want it to do. So I defined my own concept, that is invokable and returns something convertible to a boolean. But again, I struggle understanding what I can or ...
You cannot have a function that takes a "thing that can be called". It must be a "thing that can be called with some set of arguments of known (at the time of the declaration) types". That's why std::predicate takes a set of arguments in addition to the potential callable type. Your first examples work because you didn...