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
62,871,714
62,877,273
node-gyp not linking libraries correctly on macos
I'm working on a node addon but there is an error on finding libraries after building with node-gyp. here is my binging.gyp file: { "targets": [{ "target_name": "xaddon", "cflags!": [ "-fno-exceptions" ], "cflags_cc!": [ "-fno-exceptions" ], "sources": [ "cppsrc/main.cc" ], 'include_dirs...
The thing with linked 3rd-party libraries is that you'll have to provide locations to search for them. node addons are dynamically linked, shared libraries, so whenever you require an addon, the respective dynamic loader will have to load all required libraries. How can we check which libraries we require? macOS: otoo...
62,871,815
62,872,417
In c++, how do you get the input of a string, float and integer from 1 line?
An input file is entered with the following data: Juan Dela Cruz 150.50 5 'Juan Dela Cruz' is a name that I would like to assign to string A, '150.50' is a number I would like to assign to float B and 5 is a number I would like to assign to int C. If I try cin, it is delimited by the spaces in between. If I use getlin...
If we analyze the string, then we can make the following observation. At the very end, we have an integer. In front of the integer we have a space. And in front of that the float value. And again in fron of that a space. So, we can simply look from the back of the string for the 2nd last space. This can easily be achie...
62,871,904
62,872,511
Call C++ function from python and get return value
I am trying to call a C++ function from a python script. Here is my sample C++ and Python code. strfunc.cpp #include <iostream> #include <string> using namespace std; string getString() { string hostname = "test.stack.com"; return hostname; } strfunc.py import ctypes print(ctypes.CDLL('./strfunc.so').getStr...
If you use the readelf -Ws on your so file, it will give you items inside your so library: FUNC GLOBAL DEFAULT 12 _Z9getStringB5cxx11v You will see that your function is in fact there, it just has a mangled name. So proper name for calling ctype on the library would be _Z9getStringB5cxx11v(). However there are s...
62,872,470
62,873,171
checking for double threshold
I've a basic question to implement an algorithm to detect a threshold for a realtime signal. For ex. If I've a signal as shown below, I need to check if the signal crossing two thresholds in a fixed period of time, say 3 seconds. My question here is, What will be set of IF statements to check for two thresholds in a f...
First, we create a helper that detects upwards crossings: class DetectUpwardsCrossing : public QObject { public: DetectUpwardsCrossing(double threshold, QObject *parent = nullptr) : QObject(parent), threshold(threshold), current(qSNaN()) {} signals: void crossing(); public slots:...
62,872,747
62,873,326
What is the best practice for derived class destruction?
We know that the base class destructor is marked virtual for proper destruction of derived class instances as the base type pointers. Then what are the differences between the following derived class destructor practices? Simple destructor: ~Derived(); Destructor with override: ~Derived() override; Default destructor...
Primer: We expect Baseclass::~Baseclass to be virtual and class Derived to be derived public from Baseclass. Simple Destructor: That's what you will basically use if there are no other classes (and never will be) being derived from Derived. Do not declare all destructors as virtual but prefer using override keyword as...
62,872,888
62,874,960
How to get data set using python or C++
I have a data look like: So if I give the name for each row: a1 a2 b1 b2 c1 c2 d1 d2. The rule is: A B C D, you can swap position in each big row. I need to take set of 4 numbers, so I will have: a1 b1 c1 d1 a2 b1 c1 d1 a1 b2 c2 d2 a2 b2 c2 d2 a1 b1 c2 d2 a2 b1 c2 d2 a1 b1 c1 d2 a2 b1 c1 d2 a1 b2 c1 d2 a2 b2 c1 d2 a...
Mm, genetics, it's tasty... So, for solve this problem in Python you should do: Grab the data from xmls (It seems like xmls). This, just use pandas: pd.read_excel() (OPTIONAL STEP) Prepare your data. I see one cell with no value, it might cause some problem. Create indexes according you wishes (a1,a2 etc.). You can ge...
62,872,976
62,873,253
cpp Binary Search Problem, counting occurence of input element in a given array
I just want to know what the problem in this code; I got it from youtube,but the problem is when i pass the value of x. It not doing anything its showing blank screen. #include <iostream> #include <algorithm> using namespace std; // use binary search int find(int arr[], int n, int x, bool leftmost){ int low = 0;...
You are not updating your mid variable, so your loop goes infinite. Add this to the end of the loop: /... else{ low = mid +1; } mid = (low + high) / 2; // add this line Also keep things simple, the following code: int mid = low + (high - low)/2; is equivalent to : int mid = (low + high)/2; ...
62,873,079
62,873,117
pass own address while creating object in c++
I am the following code struct Me { Me(Me* a) { std::cout << "Processing " << a << std::endl; } }; int main() { Me a(&a); std::cout << "Created obj in " << &a << std::endl; Me* ak = new Me(ak); std::cout << "Created obj in " << ak << std::endl; delete ak; return 0; } and the output was Pro...
In Me a(&a); it takes an address of uninitialised variable a. The address is valid, but the object at that address doesn't exists yet. The object is considered existing once the constructor function is entered. In Me* ak = new Me(ak); ak is not initialized unit after Me constructor returns. That results in passing an i...
62,873,172
62,873,267
Initialize base class members from another base class
I tried splitting a data structure into several base classes to reuse the code and data members. There i encountered the issue that it would greatly simplify my code if i could initialize the members of one base class with the members of another. struct Base1 { const int a; Base1() : a(3) {} }; struct Base2 { co...
You'll need a clean interface. As Base2 is not related to Base1 in any way per your example, the dependency you describe shall be part of it's interface to the outward world. It is not an implementation detail. As such the correct solution would be to provide an explicit (i don't mean the keyword) constructor: Base2(in...
62,873,433
62,873,543
Send a post request with libcurl C++ question :s
I've succeeded in my GET request with libcurl, no problems! However when I try to send a post request, I'm unsure of where I put the json data, I want to be sent over.. My code looks like this, and I wonder if there is a method where I can send over the data as is: CURL* curlpost; curl_global_init(CURL_GLOBAL_ALL); c...
Use curl_easy_escape to URL encode the given C string: char* encoded = curl_easy_escape(curlpost, "{ your post data }", 0); // use "encoded" // free the memory curl_free(encoded);
62,873,533
62,889,441
How to execute QML slot from C++ without a signal?
I got a QML object in the QObject shape. With ->setProperty(..., ...) I can change properties, but how can I execute slots without signals? Currently I declare a signal in my C++ class: signals: void testSignal(); and signal/slot in QML object: signal executeTestFunc(); onExecuteTestFunc: { testAnimation.start(); ...
@Thomenson has already given a good answer on how you can connect to a signal from C++ and act on it in QML. His solution works if you can create the C++ from QML, which may not always be the case. Connections element There are two other options you might consider. First, if you have an object that was not created from...
62,873,676
62,873,923
How can i define a pure abstract base class
I get error when i try to compile this code. class FunctionVisitor { public: virtual ~FunctionVisitor() = default; virtual void visit(SumTimer&) = 0; virtual void visit(SumSelector&) = 0; }; class timerVisitor : public FunctionVisitor { private: std::string variableName; std::string variableValue;...
Every class that inherits from abstract class in c++ and doesn't override all of its pure virtual functions is considered abstract and cannot be instantiated neither locally nor dynamically. You can either override the functions to do nothing (or return an exception) virtual void visit(SumTimer& fun) override {} or ma...
62,873,726
62,889,380
Is it possible to change Radio button mark to checkmark that is left by `CheckMenuRadioItem()`?
I have a set of menu items that have to behave as exactly how radio buttons behave (once one is selected others are not marked) but the requirement is to use checkmark instead of radio button mark. Is there a possible way to modify the mark used by the CheckMenuRadioItem() function?
@AdrianMole is right. However CheckMenuItem may be altered or unavailable in subsequent versions. Instead, use SetMenuItemInfo. The following is an example for how to achieve this: case ID_MENU_ITEM1: hMenu = GetMenu(hWnd); mii.fState = MF_CHECKED; SetMenuItemInfo(hMenu, ID_M...
62,873,895
62,874,111
Non-literal within a constexpr function (via std::is_constant_evaluated)
In a constexpr function, I am unable to define a non-literal variable within the branch of an if statement conditioned by C++20's std::is_constant_evaluated()? Clang and GCC both indicate it is not permitted, but in the example below, other constructs which cannot be evaluated at compile-time are permitted. Is there a ...
There is a specific restriction. In this case a structural restriction about the bodies of constexpr functions. [dcl.constexpr] 3 The definition of a constexpr function shall satisfy the following requirements: its function-body shall not enclose a definition of a variable of non-literal type or of static or thread ...
62,874,007
62,875,662
Match template with Class Template Deduction Placeholder param
Trying to use string literals as non-type template parameters in GCC 10.1. Have the following code: #include <cstddef> #include <algorithm> #include <iostream> template<std::size_t n> struct fixed_string { constexpr fixed_string(char const (&s)[n]) { std::copy_n(s, n, this->el); } constexpr fixed_string(fixe...
It is certainly a gcc bug. I have experienced it and found this workaround: template<std::size_t n> struct fixed_string { consteval fixed_string(char const (&s)[n]) { std::copy_n(s, n, this->el); } consteval fixed_string(const fixed_string<n>& s) = default; consteval bool operator==(fixed_string...
62,874,034
66,103,826
I don't understand why I declare an empty internal structure and pass it in the constructor
When I read the source code of Hypodermic, I found an empty structure declared in the constructor of its container. I don't understand why it did this? class Container : public std::enable_shared_from_this< Container > { private: struct PrivateKey {}; public: Container(const PrivateKey&, ...
As @Eljay stated in a comment, the constructor has to be accessible when using std::make_shared. The idea behind this factory method is to make sure no component will get an instance of Container that is not a std::shared_ptr thus enforcing the legitimacy of shared_from_this() inside Container methods. If you need furt...
62,875,098
62,876,166
threading, if-else statement, both are wrong after context switch, what will happen
Example int a = 8; if(a < 9){ something1(); } else{ something2(); } what will happen if there was a context switch right before the if statment (after the init of a) which will change a to a=11, and then return to the above code, and before getting to else, another context switch which will change a to a= 8, and aga...
If a can be modified by some other thread then the code must synchronize the two threads somehow. The simplest way, which seems appropriate here, is to make a atomic: std::atomic<int> a = 8; Now multiple threads can read and write the value of a with well-defined behavior. The actual value the you see depends on the o...
62,875,132
62,875,663
How to call a function(only known at runtime) with parameter values(only known at runtime)?
At runtime a single test is made to determine which of two functions to call and also to establish parameter value(s). The function is then called every few seconds. void Foo::func( std::string s); void Foo::func( std::string s1 std::string s2, std::string s2); Obviously, its inefficient to test( which function to cal...
You can simply use a lambda function object ( closure ) which you can call as often as you like. Example: struct Foo { void func( std::string s){ std::cout << "single" << s << std::endl; }; void func( std::string s1, std::string s2, std::string s3) { std::cout << "tripple " << s1 << " " << s2 <...
62,875,209
62,875,451
Pointers and input in user define functions
In this I called a add() function by reference my doubt is how does it send input in this case. I mean does it use &p = a and does &(any variable) represent address of variable? #include<iostream> using namespace std; void add(int &p) { p++; } int main() { int a=55; add(a); cout<<a; return...
does &(any variable) represent address of variable? Yes. What are references? Simply put, references are just aliases. That means p is just another way to refer to a. Any changes you make to p or a will be reflected in the other. However, you cannot reassign the reference variable to something else. References are ju...
62,875,428
62,875,513
How to get 'static pure virtual' functionality in C++?
I'm programming Chess, and I wanted to use abstract classes for each different piece: enum class Player { Black=0, White } class Piece { protected: Player side; ... public: // I'm using a 1D array of ints to store the board, // cast() returns a list of positions where the piece can go. virtual std:...
It's not possible. With a virtual function, the exact function called depends on the type of the object you call the function on. With a static member function, there is no object on which the call is made, only a type. As such, having both makes little sense. How would the compiler know which derived type you mean to ...
62,875,482
62,876,625
Delete last printed element from console
QUESTION Given two unsorted arrays A of size N and B of size M of distinct elements, the task is to find all pairs from both arrays whose sum is equal to X. **INPUT** 1 5 5 9 1 2 4 5 7 5 6 3 4 8 **EXPECTED OUTPUT** 1 8, 4 5, 5 4 **MY OUTPUT** 1 8, 4 5, 5 4, MY CODE #include<bits/stdc++.h> using...
Replace this: for (auto x : mp) { cout << x.first << " " << x.second << ","; } with: auto it = mp.begin(); auto end = mp.end(); for (; it != end; ++it) { cout << (*it).first << ' ' << (*it).second; if ( std::next(it, 1) != end) { // check if next is end ...
62,875,657
62,875,692
Address of reference to a vector element has different address than the vector element it points to. Why?
Given the answers to the question Is the address of a reference to a dereferenced pointer the same as the address of the pointer? and my current understanding of references, I was very confused, when I checked the addresses of vector elements and compared them to the addresses of references to those elements: #include ...
This is a simple typo: the & in the declaration only applies to ref0, the others are non-reference types! Did you want const int &ref0 { vec[0] }, &ref1 { vec[1] }, &ref2 { vec[2] }, &ref3 { vec[3] }; This is more frequently fallen for with pointer declarations like int* p, q;.
62,875,738
62,876,254
Convert from vector<unsigned char> to char* includes garbage data
I'm trying to base64 decode a string, then convert that value to a char array for later use. The decode works fine, but then I get garbage data when converting. Here's the code I have so far: std::string encodedData = "VGVzdFN0cmluZw=="; //"TestString" std::vector<BYTE> decodedData = base64_decode(encodedData); char* ...
char* decodedChar; decodedChar = new char[decodedData.size() +1]; // +1 for the final 0 Why would you manually allocate a buffer and then copy to it when you have std::string available that does this for you? Just do: std::string encodedData = "VGVzdFN0cmluZw=="; //"TestString" std::vector<BYTE> decodedData = base64_d...
62,875,756
62,875,948
How to thread-safe function that adds elements to array?
I wrote the following function that accepts an object (element), makes space for it in an existing vector (elements) and updates the vector by adding the new object: void addElement(const ElementType& element) { if (numElements == elements.size()) { elements.resize(boost::extents[numElements+1]); } ...
First, let's see when the data race happens: two or more threads access the same memory location concurrently at least one of the accesses is for writing threads are not using any exclusive locks to control their accesses to that memory In your case, one thread can add the element while other thread is reading elemen...
62,875,805
62,876,476
What is the use of .cmake files in install function of CMakeLists.txt?
CMakeLists.txt ... add_library( ${PROJECT_NAME} SHARED src/run_pipeline.cpp ) target_link_libraries( ${PROJECT_NAME} ) install( TARGETS ${PROJECT_NAME} DESTINATION lib ) install( FILES ${PROJECT_NAME}Config.cmake DESTINATION lib/cmake/${PROJECT_NAME} ) That ${PROJECT_NAME}Config.cmake file is: add_library( pipeline_c...
You may find the introductory description here helpful. The <Package>Config.cmake files are package configuration files. They are useful for providing a minimal set of information about an installed package, so the consumer of the package can easily use it in their CMake project. As a package maintainer of a CMake-base...
62,875,854
62,876,134
Is there a way to get element's offset in predicates passed to std algorithms?
The predicates/operators used in the Algorithms library accept elements by the respective iterators' value_type. I would like to write a predicate that uses the element's offset in the range. For example, consider the following code: #include <algorithm> #include <vector> int main() { std::vector<int> v{0, 1, 2, 3...
Is there a "nice" way (i.e. better than what I presented above) to find the element's offset in the range? No, not in general. Is the technique above guaranteed to work for any data type Almost (except you obviously have to change the type of the argument to correspond to whatever data type is being iterated). ...
62,875,911
62,875,952
C++ Delete [] Operator
Does #include <iostream> using namespace std; int main() { float* temps = new float[10]; float* temps2 = temps; delete[] temps2; return 0; } have the same working as #include <iostream> using namespace std; int main() { float* temps = new float[10]; float* temps2 = temps; delete[] ...
Both are fine. So long as the pointer has exactly the same type (a change to or from const is allowed), you can call delete[]. (Note that for new and delete the pointer can be polymorphically related, but that's not true for new[] and delete[]).
62,876,383
62,919,497
Receiving frame from udp is too slow for face recognition
I want to receive frames from UDP port and run face recognition algorithms on them with opencv cv::dnn framework. Tello drone is sending frames over UDP protocol. /* load dnn model */ cv::dnn::Net net = cv::dnn::readNetFromCaffe("dnnmodel/deploy.prototxt.txt","dnnmodel/res10_300x300_ssd_iter_140000.caffemodel"); ...
With unreliable protocols like UDP, where the comms stack can, and will, discard data if not promptly taken out to user space, it's important to attach a high importance to reading data, even at the expense of added complexity in the recv code. In this case, a separate thread can be used to extract datagrams as soon as...
62,876,548
62,889,499
SFMLtexture shaped like player
So I've been making my own shooter in C++ using SFML library. I couldn't find a proper answer to a problem I've encountered. Is there any function in SFML that would set player and enemies sprites not to the size of their textures (just rectangles), but to the "colored" areas of the source png file so the sprite would ...
So from what I understand you probably want to create a sprite with the same bounds as your texture assuming your player is "colored" and the rest in you texture is transparent. First, your texture and the sprite (sf::Sprite) will have the same bounds as the image (png) and the scale you set, depending on the image siz...
62,876,821
62,877,230
What is a Designated Initializer?
I wish to understand what designated initializers provide that is different to direct initialization. For example: #include <iostream> struct Subject{ int x; int y; int z; }; int main() { Subject subject_d{.x = 1, .y = 2, .z= 3}; Subject subject_c{1, 2, 3}; return 0; } How can we decortic...
In the example you posted, there's absolutely no difference in terms of the behavior. The aggregate is initialized to hold the same three values. In terms of readability, an argument can be made that the designated initializer version is more explicit in terms of what is happening. It can also be used to serve a docume...
62,876,890
62,889,056
Forcing the recall of WM_PAINT
I've created a window using CreateWindowEx and that is working fine. The window opens. In the function where I process messages, specifically WM_PAINT, I grab the cursor position using GetCursorPos and then draw a rectangle there. However, I would like the window to continuously update and redraw this rectangle, acting...
First, you can get the current cursor position by processing the WM_MOUSEMOVE message and invalidate the current window. Then draw a rectangle through the Rectangle function in the WM_PAINT message. (Note: The origin of coordinates is the upper left corner of the screen) Here is the sample: #include <Windows.h> #includ...
62,877,041
62,878,111
Unable to find/read config file .conf - FileIOException
I'm trying to open and read a .conf file in my program using libconfig::readFile(), but it gives me always a FileIOException. I think that the program is unable to locate the file but I don't know where the problem is. This is the .conf file code: controlLoopPeriod = 100.0; # ms saturationMax = [10.0]; saturationMin ...
It looks to me you are missing a / at the beginning of your home path. I.e., change: std::string confPath = "home/nimblbot/tpik_ctr_algo/ctrl_rob_nimblbot"; For: std::string confPath = "/home/nimblbot/tpik_ctr_algo/ctrl_rob_nimblbot"; I take it you have checked the .conf file exists at: /home/nimblbot/tpik_ctr_algo/c...
62,877,374
62,884,823
GCC throws init-list-lifetime warning on potentially valid code?
I'm running on Debian unstable with GCC 9.3.0. There was a recent change on a project I work on that introduced code similar to what's below. #include <initializer_list> #include <map> #include <vector> std::map<int, std::vector<int>> ex = []{ /* for reused lists */ std::initializer_list<int> module_options; ...
So my understanding is that the common initializer list value, being defined within the scope of an encompassing initializer list, has a lifetime that ends with the enclosing initializer list You're talking about the object created by the prvalue expression {1, 2, 3}, right? There's an example in decl.init.list/6, T...
62,877,586
62,877,750
How to get pointer on array?
I have such an array: const char arg_arr[][100] = { "a", "b", "c", "d", }; and then I have such a method ParseCmdLine(const char *argv[]); So, in order to pass my arg_arr I need to get pointer to it. I try to invoke this method such way ParseCmdLine(*arg_arr) or like this ParseC...
Change: const char arg_arr[][100] = { ... }; To: const char *arg_arr[] = { ... };
62,878,452
62,879,010
Does GL_SHADER_STORAGE_BUFFER locations collide with other shaders locations?
I have multiple glsl files that use shader storage bufffer. If I bind buffer bases with other shader files, but they have same locations in storage buffer, they seem to affect each other. Does this mean that I have to unbind it somehow? When I chose other locations for each files, they didn't seem to have impact to the...
Buffer bindings are part of context state, not the shader program. Index 0 in the context is index 0; it's not associated with any program directly. The program only specifies which indexed binding point is used for that particular variable when the program gets used for rendering purposes. If you need to use a particu...
62,878,935
62,879,195
How to Overcome Memory Leak while throwing exception from constructor?
Is there any Memory leak in this program if yes then how to overcome this problem?? #include<iostream> using namespace std; class A { double a,b; public: A(double X,double Y) { try { a = X; b = Y; if(b==0) throw b; else cout <...
So you are not doing any dynamic allocation, it is all stack based. So it will clean up acceptably. As you are aware, your destructor is not doing anything useful. But note that throw in a constructor does not call the corresponding destructor, and if that constructor for object2 /had/ done any allocation (that you wan...
62,879,270
62,879,559
C++ Boost Asio Pool threading with lambda functions and pass by reference variables
I have a lambda function I would like to post to a boost pool. The lambda function makes use of a large object which is passed by reference. However, I can't seem to make this code run properly. #include <boost/asio.hpp> #include <iostream> int main() { int large_object = 10; auto f1 = [&large_object](int x) {...
You need to capture f1 too, just like other variables. Lambda is a variable: [x, f1]{f1(x);}); (Or by reference) By the way, if you want simple thread pool execution, consider also std::async.
62,879,275
62,897,995
Moving a shared_ptr<StructA> into a shared_ptr<variant<StructA, StructB>>
I'm trying to avoid a rather complex inheritance chain for a set of plain old data structs, but I need to store them all in a vector + share ownership with the caller. Struct A {}; Struct B {}; using TInstruction = std::variant<A, B>; struct holder { std::vector<std::shared_ptr<TInstruction>> items; }; static hold...
As per the comments, this is a somewhat silly question because the variant has to be the owner of the object for the final type to be shared_pointer<variant>. Nevin's suggestion would work but uses the void type, which has its own problems (perhaps one could use the any type? that wouldn't be better.) In the end I'm lo...
62,879,418
62,879,768
Finding a string, in a string, with regex, regex_search
I have a string: string str = "C:/Riot Games/League of Legends/LeagueClientUx.exe" "--riotclient-auth-token=yvjM3_sRqdaFoETdKSt1bQ" "--riotclient-app-port=53201" "--no-rads" "--disable-self-update" "--region=EUW" "--locale=en_GB" "--remoting-auth-token=13bHJUl7M_u_CtoR7v8XeA" "--respawn-command=LeagueClient.exe" "--res...
You should study the syntax of your expected matches to extract them correctly. To get the port number value, I'd use regex reg("--riotclient-app-port=(\\d+)"); This way, you do not even need to care about the number of digits you match since it will capture a number after a known string. If the auth token can only co...
62,879,479
62,879,722
Every call to configure_file fails on WSL: configure_file Problem configuring file
I've just built and installed cmake 3.16 on a fresh WSL install (Ubuntu18.04 LTS). I then created a default hello world project (base) ciaran@DESKTOP-K0APGUV:/mnt/d/ATest$ tree . . ├── CMakeLists.txt └── main.cpp //CMakeLists.txt cmake_minimum_required(VERSION 3.15) project(ATest) set(CMAKE_CXX_STANDARD 14) add_exec...
Create a file named wsl.conf in /etc/ with the following text: # /etc/wsl.conf [automount] options = "metadata" enabled = true Reboot wsl: wsl.exe -t Ubuntu // (or other e.g. Debian) Sources: https://intellij-support.jetbrains.com/hc/en-us/community/posts/360003413779-Troubles-with-WSL-toolchain-Test-CMake-run-fi...
62,880,020
62,896,374
reason why it doesn't works on visual 2019
I don't think there's a problem with coding grammar or composition. I drew it with my hands and checked it several times and found no particular problem. And I've tried this many times. I tried to repeat over and over, but it just shuts down immediately without any output on the run window when I use the visual studio ...
In your constructor Stack() { top->next = NULL; } top has never been given a value, so top->next is an error. Looks to me that most of your code would be fixed if you replaced top->next with top throughout. There's another error here void Stack::show() { Node *cur = new Node; cur = top-> next; You assign ...
62,880,647
62,880,681
Child class showing unknown behavior during inheritance
I am making a simple program in which I created an abstract class of shape and rectangle class is inheriting from shape class. My code is: #include <iostream> using namespace std; class shape { protected: int height; int width; public: shape(int h, int w): height(h), width(w) {}; virtual double area...
In your constructor: rectangle(int h, int w): shape(height, width) {}; instead of using the arguments h and w, you are using the existing values of height and width. Since these are not initialized, using them invokes undefined behavior, and you happen to see a result of 0. If you turn on your warnings, the compiler s...
62,880,650
62,881,016
What is the best way to round large unsigned floating point numbers to integers in C++?
I need to round a 64-bit double value to the nearest uint64_t in my code with the standard "math.h" midpoint rounding behaviour. Some of these numbers have the property: Larger than LLONG_MAX Less than or equal to ULLONG_MAX I noticed there is no 'unsigned' version of the standard library rounding functions. Also, ...
The simpliest way to round is to cast to the destination type: Imagine you want to round 2.3 to the integer root, then you do: return (int) 2.3; So, in general, you do: return (destination_type) x; However, here you have the problem that you always round down, as you can see with this 2.7 example: return (int) 2.7; =...
62,880,880
62,892,369
Creating a uniform Eigen expression with a fake size (to save memory)
I'm working on some CFD code and for some constants (such as surface roughness), I would like to provide the option of either setting it to a uniform value for the whole field, or to non-uniform values. I would prefer both options to be represented as Eigen::DenseBase derivatives, so that I can simply use function temp...
Not sure this should even be an answer, because it's equal to "RTFM". With guidance from chtz, I revisited the functionality Eigen already provides, which I had previously dismissed based on a poorly written benchmark. But it's all already there in the library: Replicate does exactly what I want.
62,880,938
62,881,072
C++ variadic templates with repeating types
Is it possible to write variadic templates or fold expressions where the function signature can be something like void f(int, string, int, string, ...) That style is very popular and user-friendly in python, but I couldn't get it to work in C++. In particular I would use it to feed a plotting function with data follow...
You can write a variadic function like this: template<typename ...Ts> void f(int data, string const &label, Ts&&... rest) { process(data, label); f(std::forward<Ts>(rest...)); } with a base case: void f() {} to terminate the recursion. Now only calls of the form: f(1, "hi"); // ok f(1, "hi", 2, "bye"); ...
62,881,513
62,881,587
Function-style casting a pointer
Chapter 4.11.3 of the book C++ Primer says the following: In early versions of C++, an explicit cast took one of the following two forms: type (expr); // function-style cast notation (type) expr; // C-language-style cast notation I get that C-style casting a pointer works like this: int* ip = nullptr; void* vp = (v...
You can use this way: using voidPointer = void*; int* ip = nullptr; void* vp = voidPointer(ip); This works because it makes the type a single word. Alternatively, this works too: typedef void* voidPointer;
62,882,804
62,883,069
Effect of heap allocation vs lack of heap allocation in a function
I've managed to write a program that implements the Game of Life using the Observer design pattern, but it seems that one of my functions, Grid::init() only works if I allocate the Cells on the heap and doesn't work otherwise. Below is the class definition for a Grid. // Grid class // Grid is initially empty. Sets up...
I think I might know what is going on. There are several problems with this code, and I think I have figured out what combination of problems is causing the behavior. Problem #1: Classes have unsafe copy constructors / copy assignment operators. In general, any class which uses pointers should override the copy constru...
62,882,877
63,074,938
lambda capture fails (on MSVC) if object has no copy constructor
Code to reproduce: struct S { S(); S(S const&) = delete; }; auto x = [s = S()]{}; It looks like MSVC doesn't apply (mandatory in C++17?) copy elision when building lambda. This breaks some of my code... Does VC's behavior violate standard?
Per "Language Lawyer"s comment: this is a known bug in MSVC that has been fixed in VS19 v16.2 and VS17 v15.8. Unfortunately (as of now) fix works only with /std:c++latest.
62,883,210
62,972,906
C++ member variable is not initialized
I have been tasked to make available a C++ codebase to a .NET application. The C++ code is used in production for a couple of years and runs without issues. I packed the C++ code in a dll and built a C based API to make it available to .NET through P/Invoke. If I test the API through a C based test application everythi...
I finally managed to find out the problem and fix it. As I said the C++ codebase is stable for a few years and already runs in production without issues so I had no reason to modify it. After I developed the C based API I tested it using a C application and it worked just fine. After that I started working on the C# ap...
62,883,813
62,884,205
Why the content of the string in initializer_list is empty?
I am using a map<string,initializer_list<string>>, but I notice that the initializer_list<string> contains empty strings, i.e. {"Red","Green","Blue"} will be {"","",""}. By replacing the initializer_list by a vector, the problem will be solved. Why did I have this behavior? std::map<std::string, std::initializer_list<s...
std::initializer_lists should normally be used only as function parameters, or in ranged-for loops. Use a proper container instead, like std::vector. Your initializer_lists are dangling. initializer_lists work like references pointing to temporary arrays, with the same lifetime extension rules: The underlying array is...
62,884,204
62,884,493
How to SFINAE using the function signature of a template function
I have a code that takes a function and executes it based on the function signature like below: template <int Num> struct Value { int value[Num]; }; struct Executor { template <int N> void do_exec(std::vector<Value<N>>& n, void (&func) (Value<N>&)) { for (auto& item : n) func(item); }...
The fix is fairly simple. Firstly, I would use std::is_invocable_v from the type traits library to test for compatible function signatures in the SFINAE mechanism. Line breaks keep the template signatures readable, I find: template< int N, typename Fn, std::enable_if_t<std::is_invocable_v<Fn, Value<N>&>>* =...
62,884,433
62,884,654
Express early termination with STL algorithms
I'm trying to rewrite some loops in my code as standard library functions. The following snippet seems to follow a general model for early termination and I'm wondering how to express that without explicit loops? auto sum = 0; for (const string& key : keys) { if (my_map.find(key) == my_map.end()) return nul...
Here's one possible approach: compute sum as the side-effect of an algorithm that terminates early. e.g. int sum = 0; auto f = std::find_if(keys.begin(), keys.end(), [&](string const &key) { if (my_map.find(key) == my_map.end()) return true; sum += m...
62,884,624
62,885,316
Using the (antiquated) C crypt() method for homework - the compiler won't link?
all: I'm supposed to use the crypt( ) function in a homework assignment. It's an old C method, which is probably pretty insecure, but it's just for demonstrative purposes. The only thing, I can't figure out how to use the dang function. I'm using CLion as my IDE on Ubuntu. It's supposed to be defined in the <crypt.h> o...
To anyone that stumbles upon this in the future, add target_link_libraries(CryptExample -lcrypt) to your CMakeLists.txt in the CLion IDE. It should be put under the add_executable(. . .) line. Replace "CryptExample" with whatever you named your project.
62,884,665
62,884,735
How can I find the first word in a vector of strings that matches a user given prefix?
Let's say I have a sorted vector of strings: std::vector<std::string> Dictionary Dictionary.push_back("ant"); Dictionary.push_back("anti-matter"); Dictionary.push_back("matter"); Dictionary.push_back("mate"); Dictionary.push_back("animate"); Dictionary.push_back("animal"); std::sort(Dictionary.begin(), Dictionary.end()...
You can write find_prefix as a lambda. That lets you capture the string you want to search for, and use that for the comparison: string word = ... // the prefix you're looking for auto result = std::find_if(Dictionary.begin(), Dictionary.end(), [&word](string const &S) { ...
62,885,279
62,885,332
cast from ‘int*’ to ‘unsigned int’ loses precision error
#include<iostream> #include<cstdlib> using namespace std; int main() { int temp = 300; cout << "Address of variable temp: " << (unsigned)&temp; return 0; } main.cpp: In function ‘int main()’: main.cpp:17:57: error: cast from ‘int*’ to ‘unsigned int’ loses precision [-fpermissive] cout << "Address of va...
You convert a pointer to int to an unsigned int. The problem is that an unsigned int is too little to contain all possible values of a pointer to int. You can try with an unsigned long long that should be great enough (unsigned long long)&temp; You can check the dimension of the type with sizeof(), that return the num...
62,885,449
62,885,713
C++ Singleton - Prevent ::instance() to variable
Given the singleton class class MySingleton { // ... public: MySingleTon& instance() { /* ... */ } }; is it possible to prevent: int main() { // the following should cause some error MySingleton& singleton = MySingleton::instance(); } while still allowing: int main() { // Only directly acc...
The only way I know to do what you are looking for is to make instance() itself be private so code that is outside of MySingleton can't call it directly, then add a static method to MySingleton that is public and uses instance() internally as needed, eg: class MySingleton { // ... private: MySingleton()...
62,885,782
62,885,865
Why does example code access deleted memory in IUnknown?
Quite a number of examples when using interfaces such as IUnknown, in this example IDocHostUIHandler but it doesn't really matter - use code similar to this: class TDocHostUIHandlerImpl : public IDocHostUIHandler { private: ULONG RefCount; public: TDocHostUIHandlerImpl():RefCount(0){ } // I...
Yes, you are correct that such examples are badly written. They need to be written more like you have described: ULONG __stdcall Release() { if (InterlockedDecrement((long*)&RefCount) == 0) { delete this; return 0; } return RefCount; } However, it is better for them to just return whatever...
62,885,808
62,885,944
Pointers in c++ and runtime errors
What is the issue with this code? It gives the output as expected, but there is a runtime error, and I don't know what it is. Can somebody explain the concept behind it? int main() { int *a = new int(7);//assume the heap memory has address 4F int *p; p = a; cout << a << endl; cout << p << endl; ...
You reassigned *p = 10 but a and p are still the same address in memory. As already mentioned, you are trying to delete the same memory space twice, which can explain the runtime error.
62,885,853
62,889,708
Is it possible to replicate MATLAB circshift approach in Armadillo?
I found this piece of code for MATLAB that lets you count neighbors for Conway's Game of Life using circshift and what I think has something to do with convolution (not too proud of my knowledge, still learning and would love your explanation of what is happening) for t=1:T neighbors = circshift(X, [1, 0]) + circshift(...
The shift() function works like in Matlab for vec types but for mat you must do it twice (in each dimension) like arma::mat circshift(arma::mat A, int r, int c) { return arma::shift(arma::shift(A,r,0),c,1); }
62,886,221
62,886,329
Can I use conditional operator to initialize C style string literal?
I'm trying to use the ternary operator (?:) to initialize a character array to either one string or another char answ[] = ans > 0 ? "Anton" : "Danik"; Where ans is just an integer obtained earlier and I keep getting the error: initialization with '{...}' expected for aggregate object Is it that you simply can't initi...
Is it that you simply can't initialize arrays through a ternary operator? Indeed, you can't. In your example, you don't want to have just array. You want to have string literal - a specific array. Unfortunately, compiler doesn't treat answ as one, because of you try to use conditional operator for initialization. Com...
62,886,497
62,886,877
Setting a pointer to `nullptr` doesn't prevent double deletes?
I have a linked list implementation, in which I have a LinkedList class which contains a member called head_ which is a pointer to a LinkedListNode. The LinkedListNode obviously contains a member called next_, which I can use to step through the list. I have a destructor ~LinkedList, which starts at the head_ and steps...
You problem is the following: ~LinkedListNode() { if (next_ != nullptr) // LINE ** delete next_; } Imagine you had a linked list 5, 4 , 3, 2, 1 and you have your head to be 5, your next would be 4, 3, and so on. When you call the function, what you will do is delete 4, and everything else will stay in you...
62,887,290
62,887,354
Tell a const char array that does not ends with '\0' apart from a C-style string in compile time
Is it possible to tell a const char array that does not ends with '\0' apart from a C-style string in compile time? Say I want to write two constructors for a class. One constructor constructs from a C-style string, which ends with '\0'. The other constructor, with different behavior, constructs from a const char array...
No, it is impossible in that way. Non-template functions are more preferable while overload resolution. C++ template functions overload resolution Nontemplate functions are first-class citizens. Why does overload of template and non-template function with the “same signature” call the non-template function? When a t...
62,887,482
62,887,632
How to convert ANSI to UTF-8?
How to convert ANSI to UTF-8 ? I use Linux socket to recv HTTP response, but there are some UTF-8 characters in the response, if I print them, I will find some error characters, like this: [ghostworker@ArchForXed b-client]$ ./get-http-response HTTP/1.1 200 OK Date: Tue, 14 Jul 2020 03:24:11 GMT Content-Type: applicatio...
I know that ANSI code cannot display UTF-8 code, how could I convert ANSI to UTF-8? There is no such encoding as "ANSI". If you mean ASCII (aka ANSI_X3.4-1968), then there is no need to do anything because ASCII is also valid UTF-8 as is. If the content is already in UTF-8 (as the charset header implies), then conver...
62,887,501
62,887,952
Using a temporary object without storing it in variable
Let's take an example where we need to insert the vector returned from a function to another vector: const std::vector<int> getvec(){ return {1, 2, 3}; } // in main... std::vector<int> foo{ 11, 12 }; auto bar = getvec(); foo.insert(foo.end(), bar.begin(), bar.end()); The fact that the bar variable needs to be ref...
Not the prettiest solution, but you could use a temporary lambda instead of a separate function, and declaring and invoking it in the same statement avoids the need for braces to limit its scope. const std::vector<int> getvec(){ return {1, 2, 3}; } // in main... std::vector<int> foo{ 11, 12 }; [&](const auto &bar)...
62,887,607
62,887,655
What is this pointer and memory code printing? I don't know if it's printing garbage or how to print the value that I need
This is a snippet of code that I took from a bigger one. I need to figure out whether or not what I'm printing is garbage and how to change it for it to print the value I need. I need it to print the value of int id instead of whatever it's printing. The output was 10813776 in this run and it, of course, changes whenev...
pMemory = new int[id]; nMemory = *pMemory; The first line replaces the array you've malloc-ed with a new uninitialized one, and then tries to read from the first slot of that new array. You shouldn't be assigning directly to pMemory; maybe to pMemory[someIndex], but not to pMemory itself. Are you trying to read from...
62,887,895
62,888,005
Sort the Array with Absolute value only and show real value In C++
Print the absolute sorted array. See the sample output for clarification. input: arr = [2, -7, -2, -2, 0] output: [0, -2, -2, 2, -7] Now I am using a lambda function as a comparator for STL std::sort but it's not giving correct answer; a help would be appreciated. Code: vector<int> absSort(const vector<int>& at) { ...
Your comparison function is incorrect. It must return a boolean indicating whether a and b are in the correct order. It should be something like this: auto compare = [](int a, int b) { int abs_a = abs(a), abs_b = abs(b); if (abs_a < abs_b) return true; if (abs_b < abs_a) return false; return a < b; }; ...
62,888,584
62,888,685
Why is privacy on a per-class basis but const doesn't work across objects of the same class?
I decided to try something out of curiosity to see how it would work. I got it into my head to see if one object of a class could access the private variables of another object of the same class. Apparently it can, if this program is any indicator: #include <iostream> using namespace std; class Colour { private: ...
const member function makes const only an object for which you call that function, that is, *this. Namely, the "hidden" parameter this of that member function is a pointer-to-const. But this does not avoid modification of col parameter. To make the other object const, simply pass it by const parameter. In your case, yo...
62,889,099
62,889,651
Can' open File in C++ under MacOs
I want to open and read a file in C++. Therefor I wrote the following code: #include <fstream> #include <iostream> #include <string> ... string line; ifstream file; file.open("./db.config"); if (file.is_open()) { cout << "File is open" << endl; getline(file, line); file.close(); }else cout << ...
The problem is, the current working directory is not the one where db.config file is located. You seem to have it in the same directory as the .cpp file. The current working directory is probably something different. Ultimately you need to decide where you want db.config file to reside, there are many options, but here...
62,889,158
62,889,600
A puzzle game from codechef
Could somebody explain the solution to this problem in cpp and how it works Can this be made more efficient using STL? http://www.codechef.com/problems/H1 It would very helpful if you could explain this particular logic along with its time complexity. #include <cstdio> using namespace std; int board[9],q[178000]={12...
It first builds a table of all the solvable boards, represented as numbers, that says how many steps from the solution that board is. Then it solves each test case by looking it up in that table. The time complexity per test case is constant. I doubt that there is anything in the standard library that could make it mor...
62,889,235
62,889,684
Modern iterating c++ collection with filter
Let say I have this class design class A {}; class B : public A {}; class C : public A {}; and a container of A like this std::list<A *> elements; Now what I want to achieve is iterate through all B objects in my container, or, in another time, iterate through all C objects. The classic way would be for (auto it = el...
A possible c++20 implementation using range #include <iostream> #include <list> #include <ranges> struct A { virtual ~A() = default; }; struct B : public A { void foo() const { std::cout << "B\n"; } }; struct C : public A {}; int main() { std::list<A *> demo{new A{}, new B{}, new C{}, new B{}}; auto is_B = []...
62,889,795
62,890,068
libquickfix.a is not generated for QuickFix C++ on linux
I am trying to build QuickFix(1.15.1) library on Linux CentOS release 6.10. I have done following steps Downloaded QuckfixFix tar quickfix-1.15.1.tar.gz Extracted tar file using command tar -xvf quickfix-1.15.1.tar.gz run command in quickfix directory: ./configure run command in quickfix directory: make Found libquick...
configure has an option: --enable-static - build static libraries So: ./configure --enable-static make -j and then you'll find the static library here: lib/libquickfix.a
62,889,877
62,890,204
does queue create a copy?
If I push an existing object into a queue: struct Node {int x; int y;}; std::vector<Node> vec; vec.push_back(Node(1, 3)); std::queue<Node> q; q.push(vec[0]); At the last line, does q store the address (pointer or reference, whatever except the object itself) of vec[0], or does it copy the whole Node object into q?
It will get copied as you assign an rvalue reference. It will get moved if you assign an lvalue reference. (temporary object). To check, use copy constructor / operator and move constructor / operator overloading: #include <iostream> #include <vector> #include <queue> struct Node { int x; int y; Node(int ...
62,890,411
62,890,479
Falsify true ↔ false
This question has no practical use! I've asked this only because I'm curious! There is a way in C++ to falsify true as false by writing somewhere #define true false, and then everywhere true in code will considered as false. But I'm seeking for a way to falsify true as false and false as true at the same time: #define ...
Perhaps something like this? #define false static_cast<bool>(1) #define true static_cast<bool>(0) Regarding undefined behavior: Those that say it is undefined are probably referring to the answer to this question: Is it legal to redefine a C++ keyword? However, if you do not use the standard C++ library, the cited r...
62,890,467
62,890,538
why is 0; a valid statement in C++?
int main() { int a; 2; 4; a; return 0; } Why is this piece of code valid (i.e. not raising any compilation error) ? What the computer does when executing 1; or a; ?
Statements like 0;, 4; are no-operations. Note that the behaviour of your program is undefined since a; is a read of the uninitialised variable a. Oops. 0, for example, is a valid expression (it's an octal literal int type with a value zero). And a statement can be an expression followed by a semi-colon. Hence 0; is a...
62,890,740
62,890,947
Can I use three ways comparison (<=>) using g++?
I want to try to use the three ways comparison operator (<=>) but... code: #include <compare> int main(){ . . . } command: g++ -std=c++2a compare.cpp output: compare.cpp:10:10: fatal error: compare: No such file or directory 10 | #include <compare> | ^~~~~~~~~ compilation terminated. I could...
Can I use three ways comparison (<=>) using g++? Yes, this does work. But remember that, as commenters note: It has to be a sufficiently recent version of GCC - 10.x at least This header, and the spaceship operator <=>, are part of the C++20 language standard. So you have to specify -std=c++20 (or -std=c++2a in earl...
62,891,169
62,891,240
Why doesn't std::unique call std::sort?
The library algorithm std::unique in C++11 can be used to rearrange an input range of a container to eliminate adjacent duplicated entries, and returns an iterator that denotes the end of the range of the unique values. This implies that if we would like to apply this to a container, we would first have to call std::so...
what's the reason for std::unique not to call std::sort? Because it’s redundant and inefficient if the input container was already sorted. The use-case of std::unique is such that it’s often (more than occasionally, at any rate) called on a sequence which is already in sorted order. Conversely, if the sequence is uns...
62,891,244
62,948,354
Reading audio in c++
i have tried to follow this method of reading an audio file into a variable. But i get the following errors: /tmp/ccvlnwCI.o: In function `main': debug_snd.cpp:(.text+0x7b): undefined reference to `sf_open' debug_snd.cpp:(.text+0xc0): undefined reference to `sf_close' debug_snd.cpp:(.text+0xec): undefined reference to ...
as @Erlkoenig mentioned, i just needed to add in $(pkg-config --libs sndfile). g++ -std=c++11 "./ReadWavFile.cpp" $(pkg-config --libs --cflags sndfile)
62,891,515
62,893,257
what's the optimum way to implement push_back without overhead
I'm trying to implement a Queue where you pass to it an Object to be added to the Queue. struct Node { T data; Node *next, *prev; }; // Push data to the back of the list. template <class T> T& CircularQueue<T>::push_back(const T&& new_data) { Node* new_node = new Node(); new_node->data = std::move(n...
you can emplace_back your Node template <class T> class CircularQueue { template<typename... U> T &emplace_back(U&&... u) { Node *new_node = new Node{{std::forward<U>(u)...}}; // <data is created here // link_node(new_node, m_head); return new_node->data; } }; void foo() { Cir...
62,891,669
62,891,976
"call to implicitly-deleted copy constructor of" error when tried to pass argument to a method
I'm, trying to use CPTL thread-pool for my application. So, i have a function with this definition: static void Invoke( int id, std::unique_ptr<BaseService> svc ); And tried to pass it to CPTL "push" method to be queued in thread-pool: pThreadPool->push( std::ref(App::Invoke), std::move( svc ) ); But I received this ...
It seems CPTL either has a bug at the line 152 or doesn't support move-only arguments (can't find any documentation on it so can't be sure): auto push(F && f, Rest&&... rest) ->std::future<decltype(f(0, rest...))> { Even though push uses std::forward<Rest>(rest)... in the invocation, it uses rest... in the SFINAE,...
62,891,955
63,202,835
What if I just dont visit the children of the queue_front node but just push them into the queue? Will it still be BFS?
https://www.hackerrank.com/challenges/ctci-bfs-shortest-reach/problem In this problem, I tried BFS by just (first approach) visiting the queue_front node and pushing its children into the queue and not visiting its children nodes instead of (second approach) visiting all its children and then pushing them into the queu...
Visiting nodes when you pop them out of the queue will be same as dfs it will not ensure you shortest path.if you will visit nodes then push it into the queue it will give you the shortest path consider the case : node 1 is connected to node 2 and node 2 with node3 and node3 with node1 in a cyclic form we will use a qu...
62,892,084
62,893,215
When is it a good idea to return a const reference in C++?
Are there any articles about when it is a good practice to use const references as return types? This is less of a question about a particular issue and more of an educative question. We are in the process of migrating to modern C++ from a somewhat rudimentary level of C and me and my colleague are tasked with mentorin...
The decision of when to return by-reference vs. by-value is not just a matter of performance, it's a matter of code semantics (although performance usually matters a lot when coding in C++). Some notable examples of returning by-reference are: a getter is often expected to return a const-reference to the actual member...
62,892,744
62,895,480
Efficient circular buffer in C++ which will be passed to C-style array function parameter
I'm seeking advice about my approach to the following problem. I have a constant input of data that I need to add to my buffer, and at every iteration, I need to pass buffered data to a function that accepts C-style array through a pointer. I'm worrying about efficiency so I pondered how could I store and manage data i...
Thank you for the answer Werner. When I run this solution on Repl.it, I get: it took an average of 21us and a max of 57382us For comparison, my original idea with the same buffer size has the following result: it took an average of 19us and a max of 54129us This means that my initial approach indeed was naive :) In t...
62,892,777
65,703,873
Create QML plugin with CMake
I'm trying to create simple QML C++ plugin using CMake. There are my sources: CMakeLists.txt: cmake_minimum_required(VERSION 2.8.12) project(qmltest LANGUAGES CXX) set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) # Path to installed Qt 5.15 set(Qt5Core_DIR ".../Qt/5.15.0/gcc_64/lib/cmake...
Qt contains 2 different base class for qml plugins: QQmlEngineExtensionPlugin (This class was introduced in Qt 5.14) and QQmlExtensionPlugin myplugin.h: #ifndef MYPLUGIN_H #define MYPLUGIN_H #include <QtQml/QQmlExtensionPlugin> #include "dummy.h" class MyPlugin : public QQmlExtensionPlugin { Q_OBJECT Q_PLUGIN_MET...
62,893,029
62,893,192
#ifdef and undeclared identifier
I develop a project in Visual Studio 2017. The following code: #ifdef MY_DEFINE #else std::string txt = "abc"; #endif output += txt; doesn't compile - I get an error: 'txt': undeclared identifier MY_DEFINE is not defined and the else branch is compiled. That code is part of the bigger project. I can't reproduce t...
You can check what's really happening using the #error directive: #ifdef MY_DEFINE #error It was defined #else #error It was NOT defined std::string txt = "abc"; #endif output += txt; It may be that MY_DEFINE is actually defined in some other header file you're including. Usually the easiest way to determine this...
62,893,543
62,893,985
Not taking Input from keyboard after using cin.getline() in C++
In the below program, it works fine when I input string of length less than or equal to 10 but when I exceed the string length, getline works fine but the subsequent input statement won't work (not taking input) /* used proper header */ int main () { int a,b; char s[10]; cin>>a; //work fine cin.ignore(); cin.getline...
Here is your solution: #include <climits> #include <iostream> using namespace std; int main() { int a, b; char s[11]; // <-- Size should be 11, the last character will be '\0' cin >> a; cin.ignore(); // better change it to cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin.getline(s, 11); //...
62,893,715
62,894,966
Template specialization by Container::value_type
I have the following two functions that I use to convert std containers to strings for logging purposes. template <typename TCollection, std::string(*ToStringFunc)(typename TCollection::value_type)> std::string LOG_COLLECTION(const TCollection& collection) { std::string as_str; for (const auto& element : collecti...
Solution - I: Using template template arguments Like @Scheff suggested in the comments, you can provide a template template function specialization for std::strings. Following is an example code: (See Online Live) #include <iostream> #include <vector> #include <string> // template alias for function pointer template<t...
62,893,892
62,904,762
Boost Test output spamming with "disabled" when running named test
I'm running a Boost Test test/suite by name, using: ./MyTestExe --run_test=my_test Unfortunately i'm getting hundreds of: "Test case "bla" is skipped because disabled" But I didn't disable it, I simply chose to not run it. Is there a way to remove all these messages? However, if possible I would like to keep them for...
Would have been nice to provide a repro. So I made the simplest one: #define BOOST_TEST_MODULE test module name #include <boost/test/included/unit_test.hpp> BOOST_AUTO_TEST_SUITE(Suite) BOOST_AUTO_TEST_CASE(A) { BOOST_TEST_MESSAGE("Yo A"); BOOST_TEST(1 == 3); } BOOST_AUTO_TEST_CASE(B)...
62,894,192
62,895,048
Detect when Socket Connection is disconnected C / C++ Unix
I know this question has been discussed several times, but I didn‘t manage to detect whether a socket disconnected in C / C++ on Unix. Is there any way to do so ? Thx, Regards from Brooks
I assume that the socket might be closed by the peer. It very depends on where you want to detect the disconnection. If you are in the blocking recv: manpage These calls return the number of bytes received, or -1 if an error occurred. In the event of an error, errno is set to indicate the error. When a stream socke...
62,894,315
62,896,773
Why does using the default template parameter for a function also used in a lambda parameter not work
Take the following peice of c++ code, which compiles fine (gcc 10.1.0) : - #include <iostream> #include <string> #include <functional> template <class T = std::string> void foo(T src, std::function<void(T&& t)> completionFn) { completionFn(std::move(src)); } int main(int argc, char *argv[]) { foo<std::string>...
The default template parameter is only used if the template CANNOT be determined from context. In the context given foo<>("hello", ...) the template T is determined to be const char [6] (as given in the error message). For functions this will always be the case for template parameters that relate to real parameters in ...
62,894,488
63,083,956
How do you compile standalone snippets in Nvidia PhysX?
I started to test PhysX by experimenting on the basic Hello World snippet shipped by the program. My installation is on Ubuntu 20.04. As I understand the source code for /home/ubuntu1/PhysX/physx/bin/linux.clang/release/SnippetHelloWorld_64 is located in /home/ubuntu1/PhysX/physx/snippets/snippethelloworld I tried to...
These were the steps I used to build PhysX SDK on Ubuntu 18.04: Install dependencies: sudo apt-get install clang, sudo apt-get install cmake, sudo apt-get install freeglut3-dev, sudo apt-get install libglew-dev, sudo apt-get install xterm and sudo apt-get install nvidia-cg-toolkit Follow the instructions in the READM...
62,894,735
62,895,264
QDateTime from string (__DATE__) invalid
When im running the following code the qdatetime is invalid: QString dateString = QString(__DATE__).simplified(); QDateTime date = QDateTime::fromString(dateString, "MMM d yyyy"); qDebug() << "Build date " << date.toMSecsSinceEpoch(); The content of dateString = Jul 14 2020 so there are no extra spaces. Why is it not...
From QDateTime::fromString() (Qt 5.12) documentation: Note: Unlike the other version of this function, day and month names must be given in the user's local language. It is only possible to use the English names if the user's language is English. Your system locale must be something other than English, so that's why ...
62,895,668
62,957,219
sqlite3_step(stmt) inside a transaction fails with error 5 without my busy-handler being called
[sqlite version 3.28.0 (2019-04-16)] I am using sqlite in a multi-threaded application. Sqlite threading-mode is configured for multi-threading (compilation flag: SQLITE_THREADSAFE=2). In accordance to that each thread is using its own database connection. In addition, since the multiple connections can access the data...
...after consulting with SQLite Forum... The solution: Replace the command BEGIN TRANSACTION with BEGIN IMMEDIATE TRANSACTION. More In sqlite there are three types of transactions: Deferred (the default) Immediate, Exclusive If the transaction-type is not explicitly specified in the BEGIN TRANSACTION statement then...
62,896,195
62,896,269
The value held by 'short int' get overflowed, but not with 'auto'?
#include <iostream> using namespace std; int main() { unsigned long maximum = 0; unsigned long values[] = {60000, 50, 20, 40, 0}; for(short value : values){ cout << "Current value:" << value << "\n"; if(value > maximum) maximum = value; } cout << "Maximum value is...
The issue is with short value when element 60000 is reached. That's too big to fit into a short on your platform, so your short is overflowed, with implementation-defined results. What seems to be happening in your case is that 60000 wraps round to the negative -5536, then converted (in a well-defined) way to an unsign...
62,896,442
63,045,311
Intel integrated performance primitives Fourier Transform magnitudes
When I am using Intel IPP's ippsFFTFwd_RToCCS_64f and then ippsMagnitude_64fc I get a massive peak at zero index in magnitudes array. My sine wave is long and main component I am interested is somewhere between 0.15 Hz and 0.25 Hz. I take the sample with 500Hz sampling frequency. If I reduce mean from the signal before...
Do I really need to address the zero index peak with mean reduction? For low frequency signal analysis a small bias can really interfere (especially due to spectral leakage). For sake of illustration, consider the following low-frequency signal tone and another one with a constant bias tone_with_bias: fs = 1; f0 = 0....
62,896,481
62,896,584
C++ member initialization
Below is the code where I'm learning the concepts of copy constructor and assignment operator. I'm referring the Bjarne Stroustrup C++11 book. But my program is crashing during when Vector class objects go out of scope. Here is the code I've written. #include <iostream> class Vector { double* elements; size_t...
There are 2 issues in your code. First, in the constructor, you are using the current size member to allocate memory. Since it's uninitialized, this invokes undefined behavior. You should use the vec.size to allocate memory: Vector::Vector(const Vector& vec) : elements { new double[vec.size] }, size { vec.size } { ...
62,896,652
62,897,468
call operator<< on temporary
Consider the following code (godbolt): #include <fstream> #include <string> #include <filesystem> namespace fs = std::filesystem; using namespace std::string_literals; template<class CharT, class Traits> void test(std::basic_ostream<CharT, Traits> &s) { s << "Other test\n"s; } struct my_struct { std::string...
So why is it possible for them to work with a temporary object? Because, unlike your operator <<, some from the standard library are not free, but member functions which can readily work on temporary objects without any problem, while the non-member functions have an explicit overload taking rvalue (or more precise, ...
62,896,681
62,897,009
Pointer to multidimensional array C++
I am trying to understand how to use pointers with multidimensional arrays (E.g: 2 dimensions, 3 dimensions...). I saw a lot of resources online for it, but I still can't seem to understand it. The syntax is also throwing me off. What do these following syntaxes mean (Why do we need parenthesis)? What does the code do ...
int (*arr)[5] : arr is pointer, pointing to an array of 5 ints int (*p)[2][2] = c; : p is a pointer, pointing to an array of 2, with each row having an array of 2 ints How does it work? Look at the following simple example: int (*array)[2] = new int[3][2]; for (int i = 0; i < 3; i++) { for (int ...
62,897,107
62,915,925
How can I create deduction guides for template aliases in C++20?
Suppose I have a class/struct template together with an explicit deduction guide for its constructor. Let this class have two template parameters of which one can get deduced by the deduction guide, for the other it can not. template <int Q, typename T> struct Foo { template <typename F> Foo(F&&) { } }; ...
To do what you want, C++ would have to be able to invert a Turing-complete subprogram. Turing-complete programs are not only not-invertible, it isn't possible to determine if a given Turing-complete program is invertible or not. You can define sublanguages where they are all invertible, but those sublanguages lack Tur...
62,897,390
62,897,666
Is there any way to use type-punning in the c-union-style with c++?
Say we have the following union: union Color{ int rgba;//assuming 32 bit int struct{ unsigned char r; unsigned char g; unsigned char b; unsigned char a; }ColorComp; }; It is indeed undefined behaviour (only in c++, not in c) to access an inactive element of the union(setting...
Yes, there is a way. Copy the bytes onto an object of type that you want to read the bytes as. There is a standard function for this: memcpy. Example: struct Color{ unsigned char r; unsigned char g; unsigned char b; unsigned char a; }; static_assert(sizeof(Color) == sizeof(std::int32_t)); std::int32_t ...
62,897,851
62,897,966
Pointer to array of pointers to array of char
I am currently studying C++ using Accelerated C++ by Koenig and i have a few troubles with the pointer to the initial array of pointers. It says in the book that the following code int main(int argc, char** argv) { // if there are arguments, write them if (argc > 1) { int i; // declare i outside the for...
A char* is a "C-string" -- it's how strings are represented in the C language. std::cout knows how to print char* because the << operator is overloaded with the implementation. C++ also has the std::string type, which is another way to represent strings.