question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
69,483,530
69,485,023
checking what I am passing and returning in a overload operator
First, I am using as reference this excellent answer on this and *this. Say I have a class: class myclass{ myclass& dosomething(){ // do something here return *this; //According to the referenced answer I am returning the same object } myclass& operator<<(myclass &mc){ ret...
You are returning the same reference that is passed as parameter. This is ok-ish, but only if thats what you want. For method chaining you typically do return *this. Consider the following to see the difference: #include <cstdlib> #include <ctime> #include <iostream> struct myclass { int value; myclass& operator...
69,483,752
69,484,010
Sorting smallest to largest number of 3 digits input only in C++ using conditional statements
My assignment is to sort the inputted 3 digits in ascending order, using conditional statements only in C++ My failed code: #include <iostream> using namespace std; int main() { int n1, n2, n3; int largest, middle, smallest; cin >> n1 >> n2 >> n3; // smallest: if (n1 < n2 && n1 < n3) { ...
if ((n1 >= n2 || n1 >= n3) && (n1 <= n2 || n1 <= n3)) { middle = n1; } else if ((n2 >= n1 || n2 >= n3) && (n2 <= n1 || n2 <= n3)) { middle = n2; } else if ((n3 >= n1 || n3 >= n2) && (n3 <= n1 || n3 <= n2)) { middle = n3; }
69,484,041
69,484,113
How to solve classical array element removal problem?
So I have a long (very long) array X if integers {1,5,3,4,1,2,2} (I keep it short for example). And I have a short array Y what holds indexes of array X to remove {1, 3, 4}. After this operation X should be {1,3,2,2}. However after removing first index the array shrinks and the Y indexes become invalidated. How do I ge...
You can search the exactly index of the values that have Y vector. When you delete the first one elemement in your case the value 1. Search the index of the second element and equals for the rest. If you search every time the index. Fexemple in your case the index that program find befor every search are. 0,1,1,
69,484,242
69,485,366
efficient bitwise sum calculation
Is there an efficient way to calculate a bitwise sum of uint8_t buffers (assume number of buffers are <= 255, so that we can make the sum uint8)? Basically I want to know how many bits are set at the i'th position of each buffer. Ex: For 2 buffers uint8 buf1[k] -> 0011 0001 ... uint8 buf2[k] -> 0101 1000 ... uint8 sum[...
An alternative to OP's naive code: Perform 8 additions at once. Use a lookup table to expand the 8 bits to 8 bytes with each bit to a corresponding byte - see ones[]. void sumit(uint8_t number_of_buf, uint8_t k, const uint8_t buf[number_of_buf][k]) { static const uint64_t ones[256] = { 0, 0x1, 0x100, 0x101, 0x10000,...
69,484,780
69,484,904
Pure virtual call from another thread using shared pointer
I am finding it very strange. Please, help me to explain this. I have a class which starts infinite loop in a separate thread, and two classes which inherit it. One of the classes implements the interface to be triggered outside as std::shared_ptr, and another one class hold this interface as std::weak_ptr. Please look...
Polymorphism doesn't work as you may expect during construction and destruction. The current type is the most derived type that still exists. When you are in Thread::~Thread the Sender part of your object has already been completely destroyed so it wouldn't be safe to call its overrides. When thread_fun tries to run lo...
69,485,568
69,485,699
Program for finding the transpose of given matrix
I was thinking the approach to finding the transpose of a matrix and below is the algorithm but it is not giving me proper output , so anyone can tell me where I have done mistake and what should be proper algorithm ? And how can I improve it ? // m is the number of rows and n is the number of columns in a matrix ...
You made the same mistake one can make while reversing a 1D array, hence I will use that as a simpler example: #include <vector> #include <iostream> #include <utility> std::vector<int> reverse_broken(std::vector<int> x){ for (size_t i=0;i< x.size(); ++i){ std::swap(x[i],x[x.size()-1-i]); } return x...
69,485,791
69,489,343
Store substring between double quotes in cpp
I am implementing the ALV tree, and I need to read input from the command line. An example of the command is as follows: insert “NAME_ANYTHING_IN_QUOTES_$” ID where NAME_ANYTHING_IN_QUOTES_$ is the data being stored in the AVL tree, and ID is used to decide if the info will be stored in the left subtree or right subtr...
I found the answer.... string name,ID,concat; getline(cin, concat); for(int i =0; i< concat.length();i++){ if(!isdigit(concat[i])&& concat[i] != 34){ name += concat[i]; } if(isdigit(concat[i])){ ID += concat[i]; } } cout<<"name is ->"<<name<<endl; cout<<"ID is ->"<<ID<<endl;
69,486,103
69,486,314
Is casting an address of int whose value overflows a singed char to a pointer to char UB?
Hello I have this example: int main(){ int x = 300; char* p = (char*)&x; printf("%s\n", p); printf("%d\n", *p); } The output: , 44 Is it Undefined Behavior casting the address of x to char* as long as x has a positive value that overflows a signed char? Why I got this output? , and 44? I've tried ...
There is no UB here. Generally, going such things violates strict aliasing (causing UB), but there is an exception allowing you to use char pointers to access any type. 300 is represented in memory as 4 bytes: 44 1 0 0 (assuming sizeof(int) == 4, which is very common, and assuming little-endianness). printf("%s\n", p);...
69,486,195
69,486,253
how to make an unnecessary long code compact using template
#include <iostream> #include <vector> #include <string> #include <tuple> #include <utility> using namespace std; class defaultValues { public: static std::tuple<bool,int,unsigned int, size_t, double, float, std::string, std::wstring > tup; static decltype(std::get<0>(tup))& getDefault(...
As long as you do not have duplicate types in your tuple, you can use the type version of get to reduce the code to class defaultValues { public: static std::tuple<bool,int,unsigned int, size_t, double, float, std::string, std::wstring > tup; template <typename T> static auto& getDefault(T) { return std::get<T...
69,486,535
69,492,001
How to Read multiple parquet files or a directory using apache arrow in cpp
I am new to apache arrow cpp api. I want to read multiple parquet files using apache arrow cpp api, similar to what is there in apache arrow using python api(as a table). However I don't see any example of it. I know I can read a single parquet file using : arrow::Status st; arrow::MemoryPool* pool = arrow::defau...
The feature is called "datasets" There is a fairly complete example here: https://github.com/apache/arrow/blob/apache-arrow-5.0.0/cpp/examples/arrow/dataset_parquet_scan_example.cc The C++ documentation for the feature is here: https://arrow.apache.org/docs/cpp/dataset.html I'm working on a recipe for the cookbook but ...
69,486,747
69,486,929
Template argument deduction failed, trying with std::variant
I have the following program similar with my problem. I need to get the specific class from a method like getClass and after that pass the object and call similar defined method. I can't use polymorphism. #include <variant> #include <optional> #include <iostream> using namespace std; class A{ public: void ...
You can use std::visit void f(const Object& ob) { std::visit([](const auto& o){ o.foo();},ob); }
69,487,009
69,487,132
Draw a transparent framebuffer onto the default framebuffer
I'm facing this situation where I need to render the content of a framebuffer object onto the screen. The screen already has some contents onto it and I would like to draw the contents of my framebuffer onto this content. I'm using Qt5 and QNanoPainter to implement this. The rendering commands I've implemented essentia...
This happens when you over-draw a semi-transparent image over itself multiple times. The white pixels become whiter, the blue pixels become bluer, and, consequently, the anti-aliased edge disappears over a couple iterations. I therefore deduce that your 'transparent framebuffer' already contains the blue line and the b...
69,487,013
69,487,147
Storing all vector values in a data type
I have a vector declared containing n integers. vector <int> tostore[n]; I want to store all the numbers in the vector inside a string in the format of their subscripts, like 12345..n Example: vector <int> store_vec{1,2,3,4,5}; int store_str; //to store the digits in order from vector store_vec cout<<store_str; D...
Instead of using an integer, which if it is 32 bits wide will only be able to store 8-9 digits, you could instead build a string that has all of the elements combined like vector <int> store_vec{1,2,3,4,5}; std::string merged; merged.reserve(store_vec.size()); for (auto num : store_vec) merged += '0' + num; // now ...
69,487,305
69,487,542
How to return a class instance on the heap, when the relevant ctor is private?
Suppose I have this struct struct MyStruct { static MyStruct Create(int x) { return { x*2, x>3 }; } MyStruct(const MyStruct& c) = delete; // no copy c'tor private: MyStruct(int a_, bool b_) : a(a_), b(b_) {} // private c'tor -- can't use new const int a; const bool b; }; Edit: I deleted the copy ...
You could wrap MyStruct in another class, which has a MyStruct member. Here's a minimal version of that: class Wrapper { public: MyStruct ms; Wrapper(int x) : ms(MyStruct::Create(x)) { } }; which you can use like so: int main() { MyStruct::Create(2); std::make_unique<Wrapper>(2); } This code will not trig...
69,487,587
69,489,218
How to pad an IP address with leading zeroes
I have seen solutions written online in C, but I want a C++ way to pad an IPv4 address with zeroes. C code found online using namespace std; #include<iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> void padZeroIP(char *str) { int oct1=0; int oct2=0; int oct3=0; int oct4=0; in...
Once again, with feeling: std::string padZeroIP(const std::string& str) { using boost::asio::ip::address_v4; auto ip = address_v4::from_string(str).to_bytes(); std::string result(16, '\0'); std::snprintf(result.data(), result.size(), // "%03d.%03d.%03d.%03d", // ...
69,487,933
69,492,999
ESP32 DevKitC Development on board LED blinking unintentionally
I wanted to create a simple HelloWorld program with my new ESP32 DevKitC Development module but I am confused that my LED is blinking even though I don't specify it in the program. My code: #include <Arduino.h> #define LED 2 int i = 0; void setup() { // put your setup code here, to run once: Serial.begin(115200)...
There are two LEDs which blink whenever there's UART traffic in either direction. You can't control them.
69,488,412
69,490,738
Retrieving file names from libssh2_sftp_readdir_ex()
I am working on a C++ code that I need to list all files and directories in a path by using the libssh2_sftp_readdir_ex() function of LIBSSH2. However, I tried to run the example (sftpdir.c) and I noticed that the code prints all files and directories along with stats, permissions and etc and I am looking for way to pr...
The libssh2_sftp_readdir_ex gives you the filename via the buffer parameter. There's no need to parse the longentry. It's indeed not really clear from the documentation. You should not try to parse the longentry for any other reason. As the libssh2 documentation say: The format of the `longname' field is unspecified ...
69,488,438
69,488,474
Keep getting 400 Bad Request: invalid header name with libcurl with the X-API-Key header
Basically, I'm just trying to run this curl command on my C++ application with libcurl. curl http://127.0.0.1:8384/rest/events -H "X-API-Key: WuCS7KQtyoRxbWDZ4zsSbjUdU4T" The command works perfectly fine on the command prompt. But when I try to use it with libcurl, I keep getting the 400 Bad Request: invalid header n...
DON'T include the -H switch when calling curl_slist_append(). That switch is meant only for the command-line curl.exe app. It tells the app that the following data should be passed to curl_slist_append(). Use this instead: curl_slist *header = curl_slist_append(NULL, "X-API-Key: WuCS7KQtyoRxbWDZ4zsSbjUdU4T");
69,488,563
69,488,741
How can reduce recursion within this function
can't figure out how to prevent recursion within this function, any suggestions or recommendations? I've tried a couple of my own solutions but ran into the error of having the program crash if wrong inputs and repeatedly entered. Thanks in advance, DK. static void CheckPlayerInput() { // gets the character entered...
Use a do while loop instead static void CheckPlayerInput() { bool invalid = false; do { invalid = false; // gets the character entered (as a char) cin >> input; ... default: { //more recursion, could cause issues // cout << "Invalid...
69,489,186
69,489,232
Is there a better way to write a vector of strings as a function's optional parameter?
I have a function where I want a const std::vector<std::string>* parameter to have a default parameter value of nullptr: // Definition. Includes a default parameter. void func(std::vector<std::string>* my_strings = nullptr); // Call site. Is there a better way? func(&std::vector<std::string>({"abc"})); Is there a bet...
If func() doesn't need to modify the vector, and you don't need to differentiate between "no vector" and "an empty vector", you could do it this way: void func(const std::vector<std::string> & my_strings = std::vector<std::string>()); ... then you can just call it naturally: func(std::vector<std::string>({"abc"})); fu...
69,489,502
69,499,347
Use case for `&&` and `||` operator overloading with regards to short-circuiting
I would like to understand better about overloading && and || operators and the loss of its short-circuit behaviour. This question stems from my attempt at implementing a lazy-evaluated data value holder of template type T. Consider such a struct, e.g. template <typename T> struct Value { // value holder & accessor ...
The question is regards to whether this would still be considered losing short-circuit behaviour of the operation. Yes, you lose the short-circuiting. In the line c = a&&b; both a and b are evaluated. This could be important if there is a possibility that evaluating b might be invalid. (Perhaps instead of b, the sec...
69,490,525
69,490,949
Garbage at the end of buffer socket
When I send 5 through a serial terminal, recv() outputs the sent data, and then corrupted garbage (5╠╠╠╠╠╠╠╠☺0). This is my code: #include <winsock2.h> #include <ws2bth.h> #include <Windows.h> #include <iostream> #include <string.h> #pragma comment(lib, "Ws2_32.lib") using namespace std; int i; unsigned int aaddr[6];...
You should NOT reinitialize Winsock, or recreate the Bluetooth socket, on every send and read. Initialize Winsock one time, preferably at app startup. And then create 1 socket and reuse it as needed. Also, you don't need the charIn[] buffer in send2() at all, as you can pass in to send(): send(btSocket, in.c_str(), (in...
69,490,633
69,492,307
creating borders in ncurses with unicode characters
Currently coding in C++ in WSL2 with ncursesw. For the box() or border() functions/macros in ncurses, is it possible to use unicode characters with them, or do they not fit in the category of chtype? I'm trying to create a border using the double line box drawing characters. If not, do I have to create a border manuall...
box and border use chtype's which provide only A_CHARTEXT bits for characters (8 bits in ncurses). To go beyond that, use box_set and border_set. Those use cchar_t structures, which you would initialize with setcchar.
69,491,034
69,491,392
Is there a C++ container that doesn't invalidate references on insertion/deletion?
I used std::vector but it end up invalidating references upon on inserts then I moved to std::deque which works great for inserts, but now the problem is that if I delete something middle of it, it end up invalidating the rest references. Is there any container that doesn't invalidate references on both insertion and d...
std::list might do what you want -- insertion does not invalidate any references or iterators on the list, and deletion just invalidates references/iterators pointing at the element deleted.
69,491,773
69,504,299
In GDB, what is the proper way to call C++ functions inside namespaces or classes in non-debug binaries?
GDB's call command normally works great for calling functions, as long as the symbols are present. But if the function is in a namespace or a class, suddenly it won't work unless it was compiled with debugging information. For example, let's say I have this program: #include <iostream> namespace ns { void test() ...
Your C++ compiler kindly put ns::test into the symbol table. All we need to do is prevent GDB's expression evaluator from trying to look up the non-existent symbol ns. To do this, put the entire function name in single quotes. (gdb) call (void)'ns::test'() ns::test
69,492,325
69,504,839
Update value in QJsonArray and write back to Json file in Qt
I have a Json file to read and display on UI. Reading is fine but when I tried to update value wheelbase, code runs with no errors but it does not update the Json Json file example { "$type": "SystemList", "$values": [ { "chassicId": 1000, "wheelbase": 98 }, { ...
You should place rootObject["$value"] = valuesArray; after the valuesArray.append(obj);. In your example, when append obj to valuesArray, you just update valuesArray, have not update rootObject. #include <QtWidgets/QApplication> #include <QDebug> #include <QFile> #include <QJsonDocument> #include <QJsonObject> #include...
69,493,035
69,493,123
Use C++ std::hash built-in specialization for plain integer array
I have data in form of arrays of 16-bit integers: uint16_t a[n] I need a hash function to store such data into an unordered_set. Now the standard library provides a built-in specialization for strings (string, u8string, u16string, ...). What I'm doing is: std::hash<std::u16string>{}(std::u16string((char16_t*)a, n)) I...
This is precisely what std::basic_string_view is for. There are specialized types as one might expect, one of which is std::u16string_view. Pass the constructor the pointer and a length. Then you can hash the resulting object.
69,493,844
69,493,964
What does struct Snake { int x, y; } snake[225]; mean?
I have this piece of code but I don't know what it means. If anyone could explain that would be helpful for me. I think this is an array of structs, am I right? struct Snake { int x, y; } s[225];
You're right. It's an array of structure Snake. You can store information of multiple Snake in there (in your code 225 snake information can be stored as you took size of the array as 225). For example: s[0].x = any_int_value; s[0].y = any_int_value; .... There're many other ways to access and assign values. To learn ...
69,493,947
69,494,119
How to use type_traits is_same for std::array
I am trying to write a validation method for a template input, which tests if the input is a std::string, std::vector, or an std::array. However for the latter I am having an issue as I must provide a constant length for the type definition. So when I call std::is_same<T, std::array<uint8_t, container.size()>>::value t...
The problem is that container.size() is not a constant expression and can't be used as non-type template argument. You can add a type trait to get the size at compile-time (or use std::tuple_size directly as @康桓瑋 commented). E.g. template <typename> struct get_array_size; template <typename T, size_t S> struct get_arra...
69,494,265
69,495,959
Is it possible to transform a future type?
Using a library that has a method like this one: std::future<bool> action(); I find my self in a situation where I have to conform with project specific enum return types like: enum Result { Ok, Failed, ConnectionDown, ServerError }; and the call site of action looks like this: std::future<Result> act() { try { ...
Waiting for continuation function (std::experimental::future::then) , you probably want something like: std::future<Result> act() { return std::async([&](){ try { if (_actor->action().get()) { return Result::Ok; } else { return Result::Failed; ...
69,494,276
69,494,352
Relation between static constant member variables and narrowing conversions in C++
Coding in C++20, using a GCC compiler. Based on the code shown below, the program will raise a narrowing conversion error/warning due to the int to char implicit conversion. However, if I add static const/constexpr to the int var {92}; line, the program runs without raising any errors/warnings. Why does this happen? W...
Why does this happen? Because list initialization (since C++11) prohibits narrowing conversions. (emphasis mine) conversion from integer or unscoped enumeration type to integer type that cannot represent all values of the original, except where source is a constant expression whose value can be stored exactly in th...
69,494,595
69,500,676
LibCurl- How to update a specific header information which is aleady set?
I need to modify a specific information like authorization token in the header request. Is there any way to update only that specific header, keeping the rest? Currently I am doing something like below. But not sure if there is any other way to do it? struct curl_slist* headers = NULL; headers = curl_s...
Usually you can't do it like you implemented it. The allocated size of test->data is unknown. Your code will work only if the header length is fixed. The libcurl code may be change, so free(test->data); test->data = strdup(newdata) is not a good idea. I would do like bellow. #include <curl/curl.h> #if LIBCURL_VERSION_...
69,494,666
69,496,604
Concept of template class in C++20
I'm new in advanced usage of templates and concepts, so here is a liitle bit complex problem: I have some Traits concept of many traits for each of Source classes: template<typename _Traits> concept Traits = requires { std::same_as<std::decay_t<decltype(_Traits::token)>, std::string_view>; }; I have some template...
Let's reduce this problem a lot. template <typename T> struct C { void f(); }; Now, your goal is to write a concept that takes any class template (e.g. C) and checks that every specialization of it has a nullary member function named f. template <template <typename> class Z> concept HasF = requires (Z<???> z) { ...
69,494,859
69,495,545
Undefined symbols for architecture x86_64 with Qt create
So I'm attempting to push data to a database for a game but i keep receiving an "Undefined symbols for architecture x86_64" error. I am rather new to c++ (just learnt today so id appreciate any help, either towards fixing my error or any code etiquette i should know. Here is the database handler .cpp: #include "databas...
As Botje said in the comments dropping the namespace{} from globalvarible.cpp fixed it.
69,496,603
69,496,766
How can std::bind bind a binary operation of two different-type parameters passed in to std::sort?
In this example I am supposed to sort a vector of strings depending on a given size, lest's say elements whose length greater than or equal to the given size come first and then the remaining. So here is what I've done: bool is_shorter(std::string const& str, std::string::size_type sz){ return !(str.size() < sz); }...
Not exactly related, but your answer is wrong: "depending, strings, supposed, example, vector, In, this, am, sort, a, of, I," Note that "In" is before "this" and "sort". Your sorting function should be comparing the sizes of the two input strings. Now, for the 'How does bind work?'. Basically, when you call std::bin...
69,497,468
69,498,038
Pausing and resuming a shell process from C++
From C++, I wish to submit a process, pause, resume it and stop it. For this, I am first using the following function to run a shell process in the background and save the associate PID. I found the function at this post (and only removed the standard input and output). int system2(const char * command) { int p_std...
Note that both SIGTSTP and SIGSTOP signals are actually pausing the process. The first can be ignored by the process but the latter can’t be. If you wish to pause the process no matter what use SIGSTOP. To kill the process, use SIGTERM or SIGKILL.
69,497,803
69,503,809
Why does C++ name lookup seem inconsistent in this example?
I have following C++ code: template <typename Type, typename T> class zz { }; class foo { template <typename T> using zz = ::zz<foo, T>; struct own_type : zz<double> { own_type(): zz<foo, double>{} {} // ERROR: needs foo arg !! }; template <typename T> struct zz_type_gen : zz<T> { z...
To allow namespace N { struct A {int f();}; } struct B : N::A { int f() {return A::f()+1;} }; without repeating the namespace qualification of A, and for the similar case of not repeating the template arguments of a class template, each class is considered to declare itself as a member (although this syntax is als...
69,498,115
69,498,591
C++20 constexpr vector and string not working
I'm getting a strange compiler error when trying to create constexpr std::string and std::vector objects: #include <vector> #include <string> int main() { constexpr std::string cs{ "hello" }; constexpr std::vector cv{ 1, 2, 3 }; return 0; } The compiler complains that "the expression must have a constant ...
Your program is actually ill-formed, though the error may be hard to understand. constexpr allocation support in C++20 is limited - you can only have transient allocation. That is, the allocation has to be completely deallocated by the end of constant evaluation. So you cannot write this: int main() { constexpr std...
69,498,716
69,498,896
What causes the overflow of the type conversion of cfloat's INT32_MIN to size_t?
Compiling the code, printed below, in Visual Studio 2019 presents the warning: C26450:... Use a wider type to store the operands. #include <iostream> #include <string> #include <cfloat> int main() { size_t b = 4; std::cout << std::boolalpha << (b < INT32_MIN) << std::endl; return 0; } the code above retu...
size_t is an unsigned format. This is due to how data is represented in memory. You would have the same behaviour whit INT32_MIN is exactly 0b10000000000000000000000000000000 which is exactly 2^31 / 2147483648 (unsigned). if you represent it as a signed 32bit number then it becomes -2^31 you should checkout : https://w...
69,498,883
69,499,161
How to locate a urdf file using parser.AddModelFromFile(full_name); in Drake
#include "drake/geometry/scene_graph.h" #include "drake/multibody/parsing/parser.h" #include "drake/common/find_resource.h" int main(void) { // Building a floating-base plant drake::multibody::MultibodyPlant<double> plant_{0.0}; drake::geometry::SceneGraph<double> scene_graph; std::string full_name = drake...
I think you have a very easy problem to resolve. You're currently using drake::FindResourceOrThrow(). If you look at its documentation, you'll note: The resource_path refers to the relative path within the Drake source repository, prepended with drake/. You have a urdf in an arbitrary location. In that case, just pas...
69,499,016
69,499,416
Using gdb to print a time_t variable
I want to print some information from gdb but don't see how. I am used to p/s p/x formats. But don't know what to do in the case below. #include<iostream> #include<climits> #include <stdio.h> #include <time.h> #include <stdint.h> using namespace std; int main() { time_t dataFrom = 1234560; cout << "dat...
Yes, as mentioned by n. 1.8e9-where's-my-share m, the execution is stopped at the line 9 and the line 10 is yet to be executed. So, a simple next or n command in gdb will run the line 10 and then if you print the value in dataFrom you can observe the proper value. GNU gdb (Ubuntu 9.2-0ubuntu1~20.04) 9.2 ... Reading sym...
69,499,372
69,499,436
C++ lambda, which was specified to capture by value, actually behaves as if it captures by reference
Looking at various examples with lambda expressions, I came across unexpected behavior for me. In this code, I expect that the variables captured by value will not change inside the lambda. Code execution shows the opposite. Can someone give an explanation. Thanks. #include <iostream> #include <functional> using names...
Capture by value only takes copies of local variables (none in your example) and this pointer. Capturing this by value is equivalent to capturing non-static data members by reference. Static member variables, like globals, are not captured at all - you are accessing them directly instead. If you actually need to keep a...
69,499,515
69,500,373
How to run current .cpp file in RAD Studio?
When I ran file1.cpp, it worked perfect. But now, I want to run test1.cpp, but it's not working. There is no option to run the second .cpp file. How can I run test1.cpp in RAD Studio?
It is clear from your screenshot that test1.cpp is not part of the currently loaded Project1 project. Only File1.cpp is. You can't just run a standalone .cpp file from the IDE. You have to add the .cpp file to a project first (in your case, simply right-click on Project1.exe in the Project Manager, choose "Add", and...
69,499,550
69,513,837
How to declare a variable as char* const*?
I have a bluez header file get_opt.h where argv is an argument: extern int getopt_long (int ___argc, char *__getopt_argv_const *___argv,..... which requires char* const* for argv. Because the unit is called from a different file I was trying to emulate argv but whatever permutation of declaring char, const and * is u...
Credit @JaMiT above [I don't know how to accept a commment] Also, you might want to notice how you can remove the call to getopt_long() from that example while retaining the error (it's motivation for your declaration, but not the source of your issue). If you think about your presentation enough, you might realize th...
69,499,724
69,499,764
Using std::memcpy to copy an object that contains a boost::any data member
I am trying to pass an object that contains a boost::any data member through a networking API to exchange data between two applications. I know that the API uses memcpy internally to copy the data, but I'm not sure if what I am trying to do is invoking undefined behavior. I wrote up a simple example to demonstrate usin...
any contains a pointer, and has a destructor, and is overall something you don't want to memcpy. It's working here because both src and dst are in the same memory space and because you’re freeing the object without running the destructor. It's potentially okay to memcpy the pointed-to object held by the any (the object...
69,500,082
69,500,235
Is there a way to specify what methods a library contains in CMake?
I have a CMake project where I'm using some options to control what the final library actually implements. Something like this (in pseudo-code): // CMakeLists.txt option(ADD_BAR "Include the bar methods" ON) configure_file(...) add_library(foo SHARED foo.cpp) // foo.cpp void doFoo(){ ... } #ifdef ADD_BAR void bar(){...
First, let's have a macro that produces a bit of code that checks whether a symbol was defined, and adds a relevant macro definition for the compiler: macro (add_definition_if_var symbol) if (${symbol}) add_compile_definitions (${symbol}) endif () endmacro () Then, it's as easy as: option (ADD_BAR "Include the...
69,500,187
69,503,009
Is there a way to embed a string in C++ source code that will show up in a core dump?
With lots of versions of binaries, if I receive a core dump, I currently rely on the sender telling me the version they were running so I can match it with the right source/symbols that built it. They are often incorrect and much time is wasted. Even asking them to send the binary with the core is error-prone. Is th...
I currently rely on the sender telling me the version they were running so I can match it with the right source/symbols that built it. Since you are talking about core dumps, it seems exceedingly likely that you are using an ELF platform (probably Linux). On an ELF platform, the standard way to identify a binary is t...
69,500,721
69,500,849
Is the address of a std::array guaranteed the same as its data?
std::array is ... (quoting from cppreference): This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member. Does that imply that the address of an array is always the same as the address of its first element, i.e. data()? #include <array> #in...
Technically, a std::array object may have padding at the beginning, in which case the data will be at a higher address than the std::array object. Only for standard-layout classes is there a guarantee that the object itself has the same address as the first non-static data member. There is no guarantee in the standard ...
69,501,052
69,501,137
How do I create a templated struct within the private section of a templated class
So I have been working on a linked list class with a node struct to go along with it. the class works when I define the templated struct before the class but it does not work when it is declared within the classes' private section. I specifically need the ListNode Struct to be defined within the class private section u...
Your struct ListNode doesn't have to be a template because it is already a nested type defined inside a template class. Just define it like this: struct ListNode { ListNode() { next = NULL; } ListNode(T value) { contents = value; next ...
69,501,077
69,501,163
std::thread in a loop results in incorrect results
I am working on a program that runs in a for loop. Since the arguments and outputs for each call is unique I though I could parallelize the calls within the loop. However this doesn't work correctly. Following is an example program that illustrates this issue #include <iostream> #include <cstdlib> #include <thread> #in...
Dont pass the counter by reference, as when it increments in main, it will increment in the thread as well. Pass it by value. void subProg1(int ii, double& emod, double& prat);
69,501,368
69,502,490
Why is an lvalue-ref overload unambiguously chosen over a forwarding-ref overload for an lvalue?
Take a look at these two overloaded function templates: template <class T> int foo(T& x) { // #1 return 1; } template <class T> int foo(T&& x) { // #2 return 2; } I call foo in the following way: int i; foo(i); // calls #1 And overload #1 is unambiguously chosen: https://gcc.godbolt.org/z/zchK1zxMW This might ...
The non language lawyer answer is that there is a tie breaker rule for exactly this case. Understanding standard wording well enough to decode it would require a short book chapter. But when deduced T&& vs T& overloads are options being chosen between for an lvalue and everything else ties, the T& wins. This was done ...
69,501,472
69,501,532
Best way to trigger a compile-time error if no if-constexpr's succeed?
I have a long series of if constexpr statements and would like to trigger a compile-time error if none of them succeed. Specifically, I have an abstract syntax tree whose result I would like to convert to a specific set of types that I might need. I have AsInt(), AsDouble(), etc. working, but I need to be able to do s...
You need to rewrite your sequence of if constexprs as a chain of if constexpr ... else if constexpr ... and have the final else clause trigger a compilation error if "reached" (i.e., not discarded). This can be done using the "dependent false idiom": if constexpr (std::is_same_v<T,int>) { return AsInt(); } else if ...
69,501,514
69,501,907
Structs in std::map<int,struct> memory leaking?
I have the following struct and map struct dataStruct{ unsigned long time; int32_t ch0; int32_t ch1; uint8_t state; int16_t temp; uint16_t vbat; int8_t rssi; }; std::map<uint32_t,struct dataStruct> uuidData = {}; And a loop which waits for new data and fills the map with it. (1) for(;;) { if (data...
Let's break down what happens with example 1 (the correct way to do this task ) uuidData[uuid] = { millis(), data_debug.get_data1(), data_debug.get_data2(), data_debug.get_state(), data_debug.get_temperature(), data_debug.get_battery_level(), ...
69,501,535
70,380,553
What's the difference between bridging a module with C++ or with JSI in React Native?
In React Native it is possible to bring native functionality from Android and iOS in multiple ways. I always thought that all possible ways were limited by platform-related languages like Java/Kotlin and Objective-C/Swift. However, I noticed that it is still possible to bridge native functionality even from C++ (withou...
The current React Native Bridge architecture between Native and JS works asynchronously and transfers data in JSON only. It produces the following issues: Async calls Many threads and jumps across them: JS, Shadow, Main, Native... JS and Main threads do not directly communicate (slow UI rendering) JSON No data shari...
69,502,392
69,502,779
How can I have a list of base class objects and access derived class fields?
Let's say I have a base class and two derived classes: class a {}; class b : a { int a; }; class c : a { int b; }; And I have a list of the base class, and I insert the derived class into the list: std::list<a> list; list.emplace_back(b()); list.emplace_back(c()); Now, I want to access int a like this: for(auto i : ...
First, you need a list of base class pointers, otherwise you will slice the objects when you insert them into the list. Then, you need to type-cast the pointers to access derived classes as needed. If all of the list elements are pointing at the same derived type, you can use static_cast: struct A {}; struct B : A { in...
69,502,413
69,503,151
Sharing Barriers across objects/threads
Lets say I have Object A and Object B. ObjA creates multiple 'ObjB's and keeps a pointer to each, then detaches a thread on each object B to do work. I want to implement a barrier in ObjA that only unlocks whenever all 'ObjB's have reached a certain internal condition within their work functions. How can I create a bar...
You can use a conditional variable. #include <iostream> #include <condition_variable> #include <thread> #include <vector> std::condition_variable cv; std::mutex cv_m; // This mutex is used for three purposes: // 1) to synchronize accesses to count ...
69,503,123
69,503,430
Error while running ns2 Simulator:-Cant read "ns_03":-No such Variable
This is my very first program on ns2 on UNIX 14.04. I am trying to build a three nodes point – to – point network with duplex links between them. Set the queue size, vary the bandwidth and find the number of packets dropped. This is my Code:- **prgrm1.tcl** set ns[new Simulator] set nf[open prg1.nam w] $ns namtrace-a...
Your error is caused by line 1 of your program: set ns[new Simulator] You're missing a space between the variable name ns and the command [new Simulator] It looks like [new Simulator] returns _o3, so the interpreter is going to run this command: set ns_o3 The Tcl set command with only one argument will return the val...
69,503,958
69,504,572
C++ - Error while usign arrays as parameter
I made a array of words and made a function to return a random word from the array. But it shows this error - hangman.cpp: In function 'std::__cxx11::string get_random_word(std::__cxx11::string*)': hangman.cpp:17:33: warning: 'sizeof' on array function parameter 'words' will return size of 'std::__cxx11::string* {aka s...
The sizeof operator may not be doing exactly what you think. According to cppreference: (sizeof) Yields the size in bytes of the object representation of type. This may include any internal members needed for the class, and not just how many characters are used in the string for example. std::string has the size() and ...
69,503,961
69,504,147
Is it possible to create different derived classes sharing the same methods that operate on member variables unique to each derived class?
I am writing an arbitrary-ranked tensor (multidimensional array) class in C++ and would like to have static and dynamic memory versions of it. However, I am struggling to think of a way to avoid having to duplicate methods in the static/dynamic versions of the class, considering that the underlying data containers woul...
You can use CRTP techniques to create a TensorBase, then convert *this to Derived& to access the derived class's Entries inside Method(): template <class Derived> class TensorBase { public: void Method() { auto& Entries = static_cast<Derived&>(*this).Entries; // Some code that operates on Entries. } }; ...
69,504,005
69,504,029
Unable to compile constexpr function with variadic arguments
I'm writing a constexpr product function with variadic arguments. I have only been able to get "Version 1" working below. When attempting to compile "Version 2", I get the error Declaration type contains unexpanded parameter pack 'data_type'. Can anyone explain why this is the case? /** Version 1. */ template <typename...
Change the return type to auto, datatype is a pack and cannot be used as return type template <typename ...data_type> constexpr auto Product2(const data_type& ..._rest) { return (_rest * ...); } int main() { constexpr auto p = Product2(1, 2, 3); return 0; }
69,504,336
69,504,410
Is there a way to use one function to replace two similar functions in C++
The following code compiles and runs fine. But, to me, there are repeated code in funtions workflow1 and workflow2.In fact, the only differences are the added parameter y in workflow2, and the different calls to method1/method2. Is there a way to use one function to replace those two? Maybe there is a way to pass a fu...
Two options: Use a lambda approach: #include <functional> class MyClass { public: void workflow1(int x) { workFlowInternal([x, this] {method1(x); }); } void workflow2(int x, int y = 1) { workFlowInternal([x, y, this] {method2(x,y); }); } private: void workFlowInternal(const std::fu...
69,504,393
69,506,312
Problem with running c++/cpp code in vscode
This two code I wrote should output the same thing, but I don't know why, when I use Function to write it, I have to put a totalDays[0] -= 1; in the line 13, and when I use Class to write it, it just works as I intended. (This problem only occurs with vscode, when I use Dev c++, it just works fine without line 13) Samp...
Answer from David C. Rankin 4 hours ago Your code exhibits Undefined Behavior. int totalDays[2]; is an Uninitialized array when totalDays[i] += d[i] + 365 * y[i]; is called. At least do int totalDays[2] = {0}; Also compile with -Wshadow enabled, you shadow the array totalDays between main() and your function in the sec...
69,504,497
69,504,978
c++ give no warning or error when a integer is passed to a function that has char arguments
Why does c++ give no warning or error when a integer is passed to a function that takes char arguments. void test(char a) { std::cout << a; } test(1); I would get unexpected behaviour doing so(ie a ? is getting printed). But I was expecting this to be an error or atleast a compilation warning as some sort of cas...
I'm not really sure why c++ allow implicit conversion here, maybe because it's good for dealing with raw memory. For why you get unexpected behavior 1 is a valid control code like '\0' or '\n' while you should use '1' (or 49, assume ASCII or compatible format) Compiler would warn if it does not fit in. void test(char...
69,505,383
69,507,637
Memory leak in C++ (Valgrind)
I implement the stack with a minimum. In this program, I get an error from valgrind. Something is wrong with the push() and main() functions. When I add delete st; to the push() function, I get even more errors. I check it through valgrind ./a.out. Sorry for the long code. I also wrote the rest of the functions for sta...
When you just delete top, you destruct it (in your case it's nothing, but you can distract yourself for reading about destructors if interested) and free the dynamic memory allocated for top. However, you actually want to also delete top->next, top->next->next (if present) etc. A hotfix: while (top) { // same as "while...
69,505,514
69,505,824
c++ print formatted 2D array
I am trying to print a 2d matrix in c++. I have a 2D array of integers. The output looks like this: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 60 0 0 0 0 0 0 0 0 0 0 60 60 60 60 60 60 60 60 60 60 100 100 100 100 100 100...
Quick code that does this, could be made better: #include <iostream> #include <string> int main() { int maxwidth = 0; int sz; std::string s; int K[3][31] = {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60,...
69,505,796
69,505,864
I can't get my code to print get volume fuction
#include <iostream> using namespace std; class Box { public: double length; double breadth; double height; void getvolume(); void setlength( double len) { length=len; } void setbreadth( double bre) { breadth=bre; } void setheight(double hei) { ...
int main() { double volume1=0.0,volume2=0.0; Box box1; Box box2; //box 1 dimensions box1.setlength(12.0); box1.setbreadth(14.7); box1.setheight(19.5); //box 2 dimensions box2.setlength(3.4); box2.setbreadth(2.2); box2.setheight(23.4); cout<<"the volume of box 1 is"; ...
69,506,688
69,507,464
Why does std::filter_view not have a way to eagerly evaluate it and convert it to view whose begin in const?
filter_view does not have a const begin. But I wonder why isn't there a member or free function on it that would return some_filter_view type that is that is same as filter_view except it has a const begin(). Obviously this method would be O(n), but it would be fine since it is explicit in code. Is it just that it is ...
This is basically "why can't we have a filter_view that caches on construction". The answer is that it will make copies O(N) since the cached iterator are iterators into the original view, so your copied view have to find begin() again for its copy. If you have a (non-const) filter_view already, then it's trivial to ma...
69,506,785
69,534,261
ebpf beginner question: bpf_trace_printk causing error?
I am new to ebpf and trying to use ebpf to inspect tcp packets. I hooked kprobe on tcp_v4_rcv() and my programs are below (just modified a helloworld program): //hello_kern.c #include <linux/tcp.h> #include <uapi/linux/bpf.h> #include <uapi/linux/tcp.h> #include "bpf_helpers.h" SEC("kprobe/tcp_v4_rcv") int bpf_prog(v...
Anyway I tried many times and finally code below works. Key points: 1. use bpf_probe_read to read address in kernel space; 2. do not use tcp_hdr(). #include <linux/tcp.h> #include <linux/skbuff.h> #include <uapi/linux/bpf.h> #include <uapi/linux/tcp.h> #include "bpf_helpers.h" SEC("kprobe/tcp_v4_rcv") int bpf_prog(str...
69,507,047
69,507,565
Why does the C++23 ranges adaptor require a callable object to be copy_­constructible?
Some ranges adaptors such as filter_­view, take_­while_­view and transform_view use std::optional's cousin copyable-box to store the callable object: template<input_­range V, copy_­constructible F> class transform_view : public view_interface<transform_view<V, F>> { private: V base_ = V(); copyable-box<F> fun_; };...
All the algorithms require copy-constructible function objects, and views are basically lazy algorithms. Historically, when these adaptors were added, views were required to be copyable, so we required the function objects to be copy_constructible (we couldn't require copyable without ruling out captureful lambdas). Th...
69,507,110
69,507,176
Should I use string or ostringstream or stringstream for fileIO in C++
I want to write to the beginning of a large file using C++ using fstreams. The method I came up with is to write the entire data to a temporary file, then writing to the original file and then copying the data from the tmp file to the original file. I want to create a buffer which will take the data from the original f...
Assuming that there are at least some operation and that you are not copying twice the same data to end with an unchanged file, the possible improvements (IMHO) are: do not use std::endl inside a loop, but only '\n' or "\n". std::endl does write an end of line, but also force an flush on the underlying stream which is...
69,507,209
69,507,332
Outputting pairs of prime numbers whose difference is 2 (from an interval) issue C++
Here is the loop that I created for checking prime numbers in a given interval and outputting those pairs whose difference is 2, problem is its still outputting some non prime numbers at the end. while (low < high) { isPrime = true; if (low == 0 || low == 1) { isPrime = false; } ...
This is the same code, but prime checking is moved into a separate function. #include <iostream> #include <string> using namespace std; bool is_prime(unsigned int n) { if (n <= 1) return false; for (int i = 2; i < n; ++i) { if (n % i == 0) { return false; } } return true; }...
69,507,388
69,507,457
How do I make this repeat?
How do I make this repeat the option after the question, for example: using std::cout; using std::cin; using std::endl; int main() { int Hero = 0, Level = 0, Melee = 0, MeleeRanged = 0, Necklace = 0, Charm = 0, Trinket = 0, ItemTotal = 0; int choice; int Loop = 0; cout << "Choose the option ...
You can use a while loop. Assuming that you are familiar with loops. But for menu driven programs, do..while is better: char ch = 'Y' do { cin >> choice; switch (choice) { case 1: ..... //your choices case 2: ..... case 3: ..... default:.... } cout << "Do you want to continue?(Y/N)";...
69,507,659
69,508,020
Kill process by pid with boost process
I do want to kill a process I have a pid of, so my code is the following: pid_t pid = 28880; boost::process::child process { pid }; std::cout << "Running: " << process.running() << "\n"; process.terminate(); I noticed though that running() always returns false (no matter what pid I take) and based on the source code t...
Boost process is a library for the execution (and manipulation) of child processes. Yours is not (necesarily) a child process, and not created by boost. Indeed running() doesn't work unless the process is attached. Using that constructor by definition results in a detached process. This leaves the interesting question...
69,507,669
69,507,776
Why it is assigning a garbage value to variable 'calc'?
This program gives a garbage value to the variable calc. Can anyone help me? What is the problem here? Code: #include <iostream> using namespace std; class trial { public: int m1; int m2; int calc = m1 + m2; void setdata(int a1, int a2) { m1 = a1; m2 = a2; } void getcalc(){ ...
The problem is how you defined calc. When a object trial is initialized, m1+m2 is assigned to calc, but m1 and m2 are not initialized themselves (they contain 'garbage'). When setdata() is called, two user-provided integers are assigned to m1 and m2, but calc is unchanged, thus the 'garbage' in the output. You need to ...
69,508,058
69,508,105
User-defined literal for stringstream
I wrote an operator function that returns std::stringstream when suffix _f appears. #include <iostream> #include <sstream> #include <utility> static std::stringstream&& operator "" _f(const char* const s, const size_t _) { return std::move(std::stringstream() << s); } int main() { const auto s = "Number: "_f ...
The operator returns a reference to a temporary std::stringstream object inside the function, resulting in a dangling reference. You should return std::stringstream directly. static std::stringstream operator "" _f(const char* const s, const size_t _) { return std::stringstream() << s; }
69,508,096
69,509,346
Binary tree and Processors (C++ Codeforces Problem)
As the title says, I am trying to solve this problem which I couldn't find a solution on Youtube or somewhere else... So here is the problem statement: Eonathan Eostar decided to learn the magic of multiprocessor systems. He has a full binary tree of tasks with height h. In the beginning, there is only one ready task ...
The problem with above code is that you are incorrectly handling the case when some of the tasks are remaining from previous level. You are assuming that all tasks must finished from one level before we move to another level. Following is corrected code. You can see it working here: #include <iostream> #include <math.h...
69,508,236
69,508,292
Problems whith assigning/printing characters in an array in a constructor throrugh a loop
I'm trying to assign characters to the hex[] array through a simple for loop in the constructor but something isn't working. It simply doesn't print anything. If I use the commented code on the other hand, it prints fine (obviously after removing the assigning loop). #define DIM 6 #include<iostream> using namespace std...
void hexnum::print() { for(int i=0; i<DIM; i++) { cout<<hex[i]; } return; } initialize i=0 so that it can iterate from starting index
69,508,795
69,509,543
My Brainf*** interpreter Does Not Work With Common Hellow World Program
I am trying to make a brainf*** interpreter in c++. when I test it with the Esolang hello world example: ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++. is is here: https://esolangs.org/wiki/Brainfuck it does not print anything for whatever reason. the period...
Thanks for your help everyone, but I found the solution. I need to change this: pos = brackets.at(brackets.size()-1); to this: pos = brackets.at(brackets.size()-1)+1;
69,509,236
69,655,065
Why does C++23 std::move_only_function not have deduction guides?
C++23 introduced std::function's cousin std::move_only_function, just like its name, it is a move-only wrapper for move-only callable objects (demo): #include <functional> #include <memory> int main() { auto l = [p = std::make_unique<int>(0)] { }; std::function<void(void)> f1{std::move(l)}; // ill-formed...
Type-erasing wrappers like move_only_function are designed to be used on API boundaries, where the types are explicit, which makes CTAD for these of dubious usefulness. Any CTAD for these callable wrappers would have to be quite limited anyway - it can't handle overloaded functions or function templates, which also mea...
69,509,249
69,511,022
Why does ASIO keep returning the same data
Hi I am writing an online multiplayer game in C++ using SFML and ASIO for networking. I was sending data back and forth between server and client and the server was sending the correct data but the client keeps acting as if it has received the same data. I have deduced this error to the fact that ASIO is caching the da...
Crystal Ball engaged: You problem is likely that you use a Dynamic Buffer (V1 or V2) concept. E.g. asio::streambuf or asio::dynamic_string_buffer/asio::dynamic_vector_buffer, usually by virtue of a member vector or string that is used with asio::dynamic_buffer(m_vec_or_string). Dynamic buffers should be consumed. For f...
69,509,784
69,509,833
Why does std::map::erase return int rather than bool?
I wonder why std::map::erase has an overload that returns an int that represents the number of elements erased; so as long as the elements are unique so the number is either 1 or 0. In this case why it doesn't return bool rather than an int? std::map<std::string, std::size_t> containers{ {"map", 1}, {"set", 10...
The answer to your question becomes obvious once you consider what std::multimap::erase() returns. That container's erase() method might return 0, it might return 1, or it might return some other value. Having an interface that's consistent across containers allows for implementation of templates and algorithms that wo...
69,510,323
69,510,790
How do I do variadic templates of variadic arguments
Problem Statement I'm trying to pass in a struct that contains a generic attribute like such template <typename Value> struct ColumnValue { std::string columnName; Value value; }; I'd also like to create a function that accepts an unknown number of parameters as such print(T... args) These args will be of the ...
The fact that ColumnValue is a template doesn't make any difference for the signature of print. We can just take a regular parameter pack and let the compiler figure out the different types. Secondly we can't loop over a parameter pack. We can however use a fold-expression. The end result would look something like this...
69,510,463
69,510,889
Binding const reference to another type
How to know if you can bind a const reference T1 to T2 ? I used to think that you can bind const reference T1 to type T2 only if T2 is convertible to T1. But since the following compiles: char x[10]; const char (&y)[10] = x; that should not be the case, since char[10] is not convertible to const char[10] (correct me i...
The standard describes the reference binding rules in [dcl.init.ref]/4 and [dcl.init.ref]/5. There is a rather long list of rules, but the bits most relevant to your question are: [dcl.init.ref]/4: Given types “cv1 T1” and “cv2 T2”, “cv1 T1” is reference-related to “cv2 T2” if T1 is similar ([conv.qual]) to T2, or T1 ...
69,510,604
69,512,277
Generics of Generic types
I am about to start learning Rust after programming in C++. I am unsure how to create a function (or anything else generic) that takes a generic type as its template argument. I have tried to compile the following code: trait Monad { fn singleton<T>(t: T) -> Self<T>; fn compact<T>(mmt: Self<Self<T>>) -> Self<T>...
Template template parameters are a limited form of higher-kinded types. Rust also has a limited form of higher-kinded types in the form of "generic associated types". These are available on the nightly. Concretely, the Monad example might look like: #![feature(generic_associated_types)] trait Monad { type Type<T>;...
69,510,628
69,510,851
Changing values of objects in std vector c++
I noticed that I am not able to change values of objects stored inside a std::vector or a std::map. The output of the code below gives "0" as a result of the toggle() function call in both cases. This behavior is not present while using the object directly, outside of the vector. Am I missing something about std::vecto...
push_back(a) makes a copy of a. mythings[0] returns a reference to that copy. As such, anything done to modify the members of mythings[0] will not be reflected in a, and vice versa. However, when a is copied by push_back(), Thing's compiler-generated copy constructor will copy the myfuncs vector as-is, and so the lambd...
69,510,798
69,516,412
valgrind leak error after deletion of all dynamic memory
I have tried to learn CPP pointer as well as to free all the memory about which I have used valgrind. But unfortunately I am getting leak error and I don't know where I am making the mistake. Also not so much idea about finding error as a human-readable way from valgrind. Any guidance to find the leak is highly appreci...
tl;dr Please check that you are using a recent Valgrind. With a combination of Valgrind and gdb you should be able to see what is going on. I get the following (FreeBSD 12.2, g++ 10.3.0, Valgrind built from git HEAD, [OS and compiler version are not relevant]). I'm using the --trace-malloc=yes option to see all the mal...
69,511,292
69,511,353
C++ how to put items in an array that is in a class
So I have a program that has a class that represents a player (also called player). The player needs to have a name, password, amount of experience, a position, and an inventory of four items. The program needs to create three (hardcoded) players each with a name, password, experience amount, position, and an inventory...
All right, first for your inventory set up, you could do it in a bunch of diverse ways, to begin within your 'setInv' function you are not receiving parameters which is weird since what are you trying to initialize your inventory with? You could initialize all values passing in an array of strings if that makes sense, ...
69,511,298
69,511,812
How does this Dijkstra code return minimum value (and not maximum)?
I am solving this question on LeetCode.com called Path With Minimum Effort: You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). Aim is to go from top left to bottom right. You can move up, down, left, or right, and you wish to find a route that re...
The problem statement requires that we find the path with the minimum "effort". And "effort" is defined as the maximum difference in heights between adjacent cells on a path. The expression max(curr_cost, wt) takes care of the maximum part of the problem statement. When moving from one cell to another, the distance to ...
69,511,412
69,511,477
Smart Pointers Destruction Issue - Unreal Engine 4.27
I've been puzzled for a couple of days now, I'm switching over to using Smart Pointer instead of raw pointers, but every time I release the last TSharePtr in order to destroy the Actor it was holding, I'm running into an assertion exception when UE4 is trying to destroy the object... Note that the object I'm destroying...
It seems the problem that was happening is that you cannot use TSharePtr (shared pointers) with UObject classes, such as AActor classes. The reason being that these are garbage collected by the engine, and cannot be garbage collected by smart pointers, as the engine GC system will block the deletion of the objects when...
69,511,685
69,926,775
ncurses curs_set(0) not working in vscode integrated terminal
Currently coding in C++20, using Ubuntu WSL2. Using the code shown below, the cursor goes invisible when running the program in WSL2 in Windows Terminal, working as intended. However, when running the program in WSL2 in vscode's integrated terminal, the cursor is visible throughout the whole program (just in case, I ev...
I was able to resolve this issue on my end by calling refresh() once first before using curs_set().
69,512,090
69,512,965
program to convert decimal to binary is not working for large outputs
I made a program to convert decimal to binary but it is not working for big outputs. I think I am not able to use long long int in my function properly. Here is my code: #include<iostream> using namespace std; int decimal_to_binary(int n) { int x=1; long long int ans=0; while (x<=n){ x*=2; } ...
You're storing a decimal number which is the binary representation of n reinterpreted as decimal. If n>2047, ans will overflow a std::int32_t; if n>524287, ans will overflow a std::int64_t (the biggest signed 64-bit number is 9223372036854775807; unsigned would allow one more bit in ans). The proper thing to return is ...
69,512,425
69,514,249
TLE in Word Search backtracking
Here is a problem from Leetcode: Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than onc...
I guess, you can do one optimization on the code to start dfs only from position where (words[i][j] == word[0]) Secondly answering your question when you pass by value every time a new copy of 2d array is created in recursive calls which gives the TLE. See My faster than 100% JAVA code, Hope this helps! class Solu...
69,512,595
69,512,795
Meson cannot find package, but pc file is where all others are found?
Currently I am getting this error trying to compile with meson: ../meson.build:96:0: ERROR: Dependency "cereal" not found, tried pkgconfig and cmake However, the cereal.pc file is located on the build directory where about a 12 more pc files are found (dependencies are downloaded through conan). Every other pc file in ...
Removing all meson files through rm -rf meson* inside the build directory and recompiling seems to have fixed the problem.
69,512,618
69,512,665
Error in making Template with Forward Declaration of functions in C++
I'm having the below class code and it is not giving Error when functions' work is defined fully in class itself #include <iostream> using namespace std; template <class user_defined_variable> class vector { int size; public: user_defined_variable *arr; vector(int si = 1, bool choice = false) { ...
When you are defining your constructor this way: vector::vector(int si = 1, bool choice = false) { arr = new user_defined_variable[size]; size = si; if (choice) { cout << "Constructor is called! and size of array is " << size << endl; } } You need to provide the template and it's arguments:...
69,513,137
69,513,295
Where is it prohibited for target object of std::function to throw on destruction?
Consider std::function definition: namespace std { template<class> class function; // not defined template<class R, class... ArgTypes> class function<R(ArgTypes...)> { public: /* ... */ template<class F> function(F&&); /* ... */ ~function(); /* ... */ }; /* ... */ } The destr...
It's a library-wide requirement, specified in [res.on.functions]: In certain cases ([...], operations on types used to instantiate standard library template components), the C++ standard library depends on components supplied by a C++ program. If these components do not meet their requirements, this document places no...
69,515,599
69,515,826
Why operator address-of has not effect?
Why does the following function call behave the same with and without the "address-of" operator? #include <iostream> void sum(int, int); void fun(int, int, void (*)(int, int)); int main() { fun(3,4, &sum); // Why does this line work with and without the `&`? return 0; } void sum(int a, int b) { cout << a...
C 2018 6.3.2.1 3 says: A function designator is an expression that has function type. Except when it is the operand of the sizeof operator, or the unary & operator, a function designator with type "function returning type" is converted to an expression that has type "pointer to function returning type". C++ performs ...
69,515,901
69,516,400
C++ loop breaked 'cause the std::find algorithm
I have the next C++ code snippet: ... static constexpr const char* my_char_array [10] { // Some literals here... } // Member of a class std::vector<std::string> splitted_input { // Contains C++ strings } std::vector<std::string> matched_keywords { // The coincident ones will be copied here } for (int i = 0; i < sizeof...
In this line: for (int i = 0; i < sizeof(this->my_char_array); i++) { you are using sizeof operator which is returning number of bytes which my_char_array occupies, and this is equal to size of pointer (8 bytes on x64 system) multiplied by number of pointers in your array. So this code is iterating over more elements ...
69,515,967
69,516,853
Does the following function and function call insert "seat" after "driver_seat"
I'm relatively new to programming in c++ and I'm working on a complex project for one of my classes. I need to know if my definition of my function insertAfter works as intended and if I'm using it correctly. void SeatNode::insertAfter(SeatNode* node) { // insert this->SeatNode after node this->next_node = node...
No, it doesn't. I'll go through it step by step starting at the point you call insertAfter(): You change the next pointer of the seat to the one after the driver, so far so good. You change the next pointer of the driver to the next pointer of the seat which is the pointer that you just changed to the one after the dr...
69,516,333
69,516,578
basic calculator, using Reverse Polish Notation
I'm trying to make a basic calculator, using Reverse Polish Notation that gets input from string and outputs a double. Input is: 82+5*8-4/ what should be read as (((8 + 2) * 5) - 8) / 4 in Standard notation. The wanted output is 10.5 but my output is 106.962. Can you explain to me what I'm doing wrong? As far as i can ...
Using the comments, i got it working now: #include <iostream> int main() { std::string input = "82+5*8-4/"; double output, num1; num1 = input[0] - '0'; for (int i = 1; i < input.size() - 1; i = i + 2) { double num2 = input[i] - '0'; switch (input.at(i + 1)) { case '+...
69,516,437
69,540,949
Load from IPersistMoniker takes long time to load unresolvable URL
I am loading an local disk drive _test.htm file through IPersistMoniker Load method. From what I believe, it is supposed to add the path to the relative URLs as base path. Problem is - it does not do so. Instead, it takes a very long time trying to resolve the path from Internet until it gives up (about 20-30 seconds)....
Update - this doesn't work well! The code below doesn't work well! The problem is - it loses <BODY> tag attributes. BODY tag turns out entirely empty after loading. I ended up loading the message using IHTMLDocument2.write method. See: Assigning IHTMLDocument2 instance to a TWebBrowser instance After spending lots of...