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){ return mc; // HERE, am I returning the same object?? } }; int main(){ myclass myobject; myobject << myobject.dosomething(); } My question is, in the overload operator, I am passing a reference as aan argument, right? And I am returning the same object, is this correct?
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<<(myclass &mc) { std::cout << value << " << " << mc.value << "\n"; return mc; } myclass& operator>>(myclass& mc){ std::cout << value << " >> " << mc.value << "\n"; return *this; } }; int main(){ myclass m1{1},m2{2},m3{3}; m1 << m2 << m3; std::cout << "\n"; m1 >> m2 >> m3; } Output: 1 << 2 2 << 3 1 >> 2 1 >> 3 Maybe it also helps to realize that the two lines can also be written as: m1.operator<<(m2).operator<<(m3); m1.operator>>(m2).operator>>(m3); Usually one expects that m1 >> m2 >> m3; resolves to chained calls on m1, ie first m1 >> m2 then m1 >> m3. Only when it is clear from context and semantics of myclass you should make m1 << m2 << m3; call first m1 << m2 and then m2 << m3. Operator overloading is very permissive, you can do very weird things if you like, but it might lead to surprises when the user expects your operator<< to chain as usual.
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) { smallest = n1; } else if (n2 < n1 && n2 < n3) { smallest = n2; } else if (n3 < n1 && n3 < n2) { smallest = n3; } cout << smallest; // middle: 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; } cout << " " << middle; // largest: if (n1 > n2 && n1 > n3) { largest = n1; } else if (n2 > n1 && n2 > n3) { largest = n2; } else if (n3 > n2 && n3 > n1) { largest = n3; } cout << " " << largest; return 0; } Input: 6 1 3 My Output: 1 0 6 Expected Output: 1 3 6 As you can see, I couldn't figure out how to sort the middle digit to be sorted to the middle of the 3 digits. I don't have a problem with the largest and smallest digits since I can use < and > to them, except for the middle.
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 get around this? All that comes to my mind are recreating strategies (like inclusion and exclusion), but with a long array it's very inefficient.
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[k*8]-> 0 1 1 2 1 0 0 1... are there any BLAS or boost routines for such a requirement? This is a highly vectorizable operation IMO. UPDATE: Following is a naive impl of the requirement for (auto&& buf: buffers){ for (int i = 0; i < buf_len; i++){ for (int b = 0; b < 8; ++b) { sum[i*8 + b] += (buf[i] >> b) & 1; } } }
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, 0x10001, /* 249 more pre-computed constants */ 0x0101010101010101}; uint64_t sum[k]; memset(sum, 0, sizeof sum): for (size_t buf_index = 0; buf_index < number_of_buf; buf_index++) { for (size_t int i = 0; i < k; i++) { sum[i] += ones(buf[buf_index][i]); } } for (size_t int i = 0; i < k; i++) { for (size_t bit = 0; bit < 8; bit++) { printf("%llu ", 0xFF & (sum[i] >> (8*bit))); } } } See also @Eric Postpischil.
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 at the code below. Sorry for a lot of code, I was trying to be as short as it possible to reproduce the error. Why sometimes have I pure virtual call in Sender::notify function? As far as I know std::shared_ptr is reentrant. #include <iostream> #include <memory> #include <thread> #include <atomic> #include <list> #include <mutex> class Thread : private std::thread { std::atomic_bool run {true}; public: Thread() : std::thread([this](){ thread_fun(); }) {} void thread_fun() { while (run) loop_iteration(); } virtual void loop_iteration() = 0; virtual ~Thread() { run.exchange(false); join(); std::cout << "Thread released." << std::endl; } }; class Sender : public Thread { public: class Signal{ public: virtual void send() = 0; virtual ~Signal(){} }; void add_receiver(std::weak_ptr<Signal> receiver) { std::lock_guard<std::mutex> lock(receivers_mutex); receivers.push_back(receiver); } void notify() { std::lock_guard<std::mutex> lock(receivers_mutex); for (auto r : receivers) if (auto shp = r.lock()) shp->send(); //Somethimes I get the pure virtual call here } private: std::mutex receivers_mutex; std::list<std::weak_ptr<Signal>> receivers; void loop_iteration() override { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); notify(); } }; class Receiver : public Thread, public Sender::Signal { std::atomic_bool notified {false}; public: void send() override { notified.exchange(true); } private: void loop_iteration() override { std::this_thread::sleep_for(std::chrono::milliseconds(250)); std::cout << "This thread was " << (notified? " " : "not ") << "notified" << std::endl; } }; int main() { std::shared_ptr<Thread> receiver = std::make_shared<Receiver>(), notifier = std::make_shared<Sender>(); std::dynamic_pointer_cast<Sender>(notifier)->add_receiver( std::dynamic_pointer_cast<Sender::Signal>(receiver)); receiver.reset(); notifier.reset(); return 0; }
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 loop_iterator() before the constructor finishes or after the destructor starts, it will not polymorphically dispatch, but instead it will call Thread::loop_iteration which is a pure virtual function (= 0). See https://en.cppreference.com/w/cpp/language/virtual#During_construction_and_destruction Here is a demonstration of this : https://godbolt.org/z/4vsPGYq97 The derived object is destroyed after one second, at which point you see the output change indicating that the virtual function being called changes at that point. I'm not sure if this code is valid, or if destroying the derived part of the object while one of its member function is being executed is Undefined Behavior.
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 for (int i = 0; i < m; i++) // For swapping the non-diagonal elements { for (int j = 0; j < n; j++) { if (i != j) { int temp = 0; temp = a[i][j]; a[i][j] = a[j][i]; a[j][i] = temp; } } } cout << "Elements of transpose matrix of a is: " << endl; for (int i = 0; i < m; i++) // printing the elements after transpose { for (int j = 0; j < n; j++) { cout << a[i][j] << " "; } cout << endl;
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; } int main(){ auto x = reverse_broken({1,2,3,4}); for (const auto& e : x) std::cout << e << " "; } output: 1 2 3 4 reverse_broken iterates all elements and swaps them with the respective reversed element. However, once the first has been swapped with the last, the last has already been swapped. Later swapping the last with the first puts them in the original order again. Same with your transpose. Once you swapped an element above the diagonal with one below the diagonal, they are already transposed. You don't need to swap them again. I'll show you the fix for the reverse_broken and leave it to you to apply same fix to your transpose: std::vector<int> reverse(std::vector<int> x){ for (size_t i=0;i< x.size()/2; ++i){ // stop in the middle ^^ because then all elements have been swapped std::swap(x[i],x[x.size()-1-i]); } return x; } You should also consider to not transpose the matrix at all. Depending on how often you access swapped elements and how you populate it, it will be cheaper to either populate it in right order from the start, or just swapping the indices on access: // normal access: auto x = a[i][j]; // transposed access: auto y = a[j][i]; PS: I used reverse only for illustration. To reverse a container you should actually use std::reverse. Also note that you can and should use std::swap. And last but not least, only a square matrix can be transposed in place. For a non square matrix you need to construct a new one with different dimensions.
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 subtree. Code snipet is as follows: if (comand == "insert") { int ID = 0; string Name; cin >> Name; cin >> ID; root = insertInfo(root, Name, ID); } I can not figure out how to scan in the substring that is between two double-quotes. Thanks.
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 to understand so I thought 300 % 256 = 44 is converted and assigned to p so its character ASCII value is , on my implementation. What do you think and recommend?
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); interprets those 4 bytes as a C-string. You would get the same result by printing const char str[4] = {44, 1, 0, 0}; // Same as `{',', '\1', '\0', '\0'}` In theory, you could get UB if the byte representation of 300 didn't contain null bytes, as it would cause printf to continue reading memory out of bounds of x, looking for a null-terminator. But there are no real platforms where that's the case, so it should be safe. And *p accesses the first byte in the representation of x, which is 44. If you were to try this code on a big-endian platform, you would get an empty string and a 0 respectively, since the byte representation of 300 would be 0 0 1 44. x has a positive value that overflows a signed char This isn't a problem.
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(bool ) { return std::get<0>(tup); } static decltype(std::get<1>(tup))& getDefault(int ) { return std::get<1>(tup); } static decltype(std::get<2>(tup))& getDefault(decltype(std::get<2>(tup) )) { return std::get<2>(tup); } static decltype(std::get<3>(tup))& getDefault(decltype(std::get<3>(tup))) { return std::get<3>(tup); } static decltype(std::get<4>(tup))& getDefault(double ) { return std::get<4>(tup); } static decltype(std::get<5>(tup))& getDefault(decltype(std::get<5>(tup)) ) { return std::get<5>(tup); } static decltype(std::get<6>(tup))& getDefault(decltype(std::get<6>(tup)) &) { return std::get<6>(tup); } static decltype(std::get<7>(tup))& getDefault(decltype(std::get<7>(tup)) &) { return std::get<7>(tup); } }; std::tuple<bool,int,unsigned int, size_t, double, float, std::string, std::wstring> defaultValues::tup = std::make_tuple(false,int(0),0,size_t(0), double(0.0),float(0.0),std::string(""),std::wstring(L"")); int main() { std::cout<<defaultValues::getDefault(false)<<std::endl; // your code goes here return 0; } Now I have some questions, I feel the code should be compressible using templates. I tried something like template<int N> static decltype(std::get<N>(tup))& getDefault(bool ) { return std::get<N>(tup); } to replace the functions but it did not work. Why can't I use decltype<std::get<0>> instead of bool in the first function. When I do that I get some ambiguity and the compiler complains. I would appreciate all input I can get.
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>(tup); } };
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::default_memory_pool(); arrow::fs::LocalFileSystem file_system; std::shared_ptr<arrow::io::RandomAccessFile> input = file_system.OpenInputFile("/tmp/data.parquet").ValueOrDie(); // Open Parquet file reader std::unique_ptr<parquet::arrow::FileReader> arrow_reader; st = parquet::arrow::OpenFile(input, pool, &arrow_reader); Please let me know if you have any questions. Thanks in advance
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 I can post some snippets here. These come from this work-in-progress: https://github.com/westonpace/arrow-cookbook/blob/feature/basic-dataset-read/cpp/code/datasets.cc Essentially you will want to create a filesystem and select some files: // Create a filesystem std::shared_ptr<arrow::fs::LocalFileSystem> fs = std::make_shared<arrow::fs::LocalFileSystem>(); // Create a file selector which describes which files are part of // the dataset. This selector performs a recursive search of a base // directory which is typical with partitioned datasets. You can also // create a dataset from a list of one or more paths. arrow::fs::FileSelector selector; selector.base_dir = directory_base; selector.recursive = true; Then you will want to create a dataset factory and a dataset: // Create a file format which describes the format of the files. // Here we specify we are reading parquet files. We could pick a different format // such as Arrow-IPC files or CSV files or we could customize the parquet format with // additional reading & parsing options. std::shared_ptr<arrow::dataset::ParquetFileFormat> format = std::make_shared<arrow::dataset::ParquetFileFormat>(); // Create a partitioning factory. A partitioning factory will be used by a dataset // factory to infer the partitioning schema from the filenames. All we need to specify // is the flavor of partitioning which, in our case, is "hive". // // Alternatively, we could manually create a partitioning scheme from a schema. This is // typically not necessary for hive partitioning as inference works well. std::shared_ptr<arrow::dataset::PartitioningFactory> partitioning_factory = arrow::dataset::HivePartitioning::MakeFactory(); arrow::dataset::FileSystemFactoryOptions options; options.partitioning = partitioning_factory; // Create a dataset factory ASSERT_OK_AND_ASSIGN( std::shared_ptr<arrow::dataset::DatasetFactory> dataset_factory, arrow::dataset::FileSystemDatasetFactory::Make(fs, selector, format, options)); // Create the dataset, this will scan the dataset directory to find all of the files // and may scan some file metadata in order to determine the dataset schema. ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::dataset::Dataset> dataset, dataset_factory->Finish()); Finally, you will want to "scan" the dataset to get the data: // Create a scanner arrow::dataset::ScannerBuilder scanner_builder(dataset); ASSERT_OK(scanner_builder.UseAsync(true)); ASSERT_OK(scanner_builder.UseThreads(true)); ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::dataset::Scanner> scanner, scanner_builder.Finish()); // Scan the dataset. There are a variety of other methods available on the scanner as // well ASSERT_OK_AND_ASSIGN(std::shared_ptr<arrow::Table> table, scanner->ToTable()); rout << "Read in a table with " << table->num_rows() << " rows and " << table->num_columns() << " columns";
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 foo() const { std::cout << "A"; } }; class B{ public: void foo() const { std::cout << "B"; } }; class C { public: void foo() const { std::cout << "C"; } }; using Object = std::variant<A,B,C>; std::optional<Object> getClass(int nr) { if (nr == 0) return A{}; else if (nr == 1) return B{}; else if(nr == 2) return C{}; return std::nullopt; } void f(const Object& ob) { //how to call foo function ??? } int main() { const auto& obj = getClass(2); if (obj.has_value()) f(obj.value()); }
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 essentially take a QOpenGLFramebufferObject and converts this into a QNanoImage (using this) and then calls QNanoPainter::drawImage. This works ok but the problem is that when the content of the fbo is rendered onto the screen, the previously existing content of the screen becomes "pixelated". So for example, before I draw the FBO the screen looks like this Then when I draw the FBO onto the default render target, I get this (red is the content of FBO) I assume this has something to do with blending and OpenGL, but I'm not sure how to solve this problem.
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 black grid lines. The solution thus will be to clear the 'transparent framebuffer' before you proceed with drawing the red line into in.
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; Desired Output: 12345 How do I store it in store_str without printing it?
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 merged is "12345"
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 constructor. This is simplified example of some classes I have in my codebase where they don't have copy c'tors. I can get an instance on the stack like so: int main() { auto foo = MyStruct::Create(2); return 0; } But suppose I need a pointer instead (or unique_ptr is fine), and I can't change the implementation of MyStruct, how can I do that?
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 trigger any copies nor moves - because of copy elision (see: What are copy elision and return value optimization?). You can then add any other constructors and methods you like to such a wrapper, possibly forwarding some of the method calls to the ms member. Some might choose to make ms protected or private.
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; int i = 0; const char s[2] = "."; char *token; /* get the first token */ token = strtok(str, s); oct1 = atoi(token); /* walk through other tokens */ while( token != NULL ) { token = strtok(NULL, s); if(i==0) oct2 = atoi(token); else if(i==1) oct3 = atoi(token); else if(i==2) oct4 = atoi(token); i++; } sprintf(str,"%03d.%03d.%03d.%03d",oct1,oct2,oct3,oct4); }
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", // ip[0], ip[1], ip[2], ip[3]); result.resize(15); return result; } This doesn't assume input is valid and doesn't reinvent the wheel. See it Live On Coliru: 127.0.0.1 -> 127.000.000.001 1.1.1.1 -> 001.001.001.001 OVERKILL Keep in mind that IPv4 addresses can take many forms, E.g. 127.1 is valid for 127.0.0.1. So is 0177.1 or 0x7f.1
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); pinMode(LED, OUTPUT); digitalWrite(LED, LOW); } void loop() { i++; Serial.print("I am running and calculating:"); Serial.println(i); delay(1000); } My environment: [env:esp32dev] platform = espressif32 board = esp32dev framework = arduino monitor_speed = 115200 I can see in my terminal the Serial.print output with the correct i values: But the on board LED is still blinking even though on line 11 I specifically set the pin to LOW. Strange thing is that the LED is blinking perfectly in sync with the Serial.print output. I am using VS code with PlatformIO, I have tried erasing the flash, rebuilding the program, cleaning it, uploading and nothin helped (even tried the verbose build and verbose upload). What can be the cause of this?
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 print only file and directories names. Basically, I am trying get the file names from an vector of strings in C++ that contains the output generated by the libssh2_sftp_readdir_ex() command. The entries look like this: drwxr-xr-x 2 sftpuser sftpgroup 318 Sep 29 13:33 . drwxr-xr-x 4 root root 36 Aug 6 22:18 .. -rw-r--r-- 1 sftpuser users 607 Aug 9 17:48 sample1.txt -rw-r--r-- 1 sftpuser users 1311881 Aug 9 17:48 sample1.docx -rw-r--r-- 1 sftpuser users 29380 Aug 9 17:48 sample1.xlsx -rw-r--r-- 1 sftpuser users 120515 Aug 9 17:48 sample2.docx -rw-r--r-- 1 sftpuser users 32924 Aug 9 17:48 sample2.xlsx -rw-r--r-- 1 sftpuser users 34375 Aug 9 17:49 sample3.docx -rw-r--r-- 1 sftpuser users 3541 Aug 9 17:49 sample3.txt -rw-r--r-- 1 sftpuser users 13246 Aug 9 17:49 sample3.xlsx -rw-r--r-- 1 sftpuser users 14169117 Aug 9 17:49 sample4.docx -rw-r--r-- 1 sftpuser users 2069007 Aug 9 17:49 sample_1280×853.png -rw-r--r-- 1 sftpuser users 4767276 Aug 9 17:49 sample_1920×1280.png -rw-r--r-- 1 sftpuser users 35898398 Aug 9 17:49 sample_5184×3456.png -rw-r--r-- 1 sftpuser users 534283 Aug 9 17:49 sample_640×426.png -rw-r--r-- 1 sftpuser users 20 Aug 31 18:56 testedown.txt Currently I have implemented this code below that should parse each string in an vector (LSEntriesFull) to an another vector (LSEntriesBrief) that get only the file names: const std::regex separator("\\s+"); // Each element of LSEntriesFull we need to do the parsing for (auto & it : LSEntriesFull) { std::regex_token_iterator<std::string::iterator> itr(it.begin(), it.end(), separator, -1); std::regex_token_iterator<std::string::iterator> end; while (itr != end) { // Lets print to stderr to check if its ok std::cerr << " [" << *itr++ << "]"; // TODO: Filter in an optimal way only the file names LSEntriesBrief.emplace_back(*itr++); // WRONG!!! It is getting all elements } } What is the best optimal way to do this parsing in order to get only the filenames from the vector (LSEntriesFull) and to put into the other vector (LSEntriesBrief)?
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 by SFTP protocol. The longentry is for display only (to be "parsed" by the human reader). Check the libssh2 sftpdir.c example. When the libssh2_sftp_readdir_ex returns any longdesc, the example code prints it as it is. When not, it assembles display information from buffer (mem in the example) and the attrs (LIBSSH2_SFTP_ATTRIBUTES).
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 name error. I browsed through a few other similar threads, but I could not find the solution. I'm really at my wits end now. :( The spacing and syntax looks good.... thanks for the help. Here's the code: static size_t my_write( void* buffer, size_t size, size_t nmemb, void* param ) { std::string& text = *static_cast< std::string* >( param ); size_t totalsize = size * nmemb; text.append( static_cast< char* >( buffer ), totalsize ); return totalsize; } int main() { std::string result; CURL* curl; CURLcode res; curl_global_init( CURL_GLOBAL_DEFAULT ); curl = curl_easy_init(); if ( curl ) { curl_easy_setopt( curl, CURLOPT_URL, "http://127.0.0.1:8384/rest/events" ); curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, my_write ); curl_easy_setopt( curl, CURLOPT_WRITEDATA, &result ); curl_easy_setopt( curl, CURLOPT_VERBOSE, 1L ); struct curl_slist *header = NULL; header = curl_slist_append( header, "-H \"X-API-Key: WuCS7KQtyoRxbWDZ4zsSbjUdU4T\"" ); curl_easy_setopt( curl, CURLOPT_HTTPHEADER, header ); res = curl_easy_perform( curl ); curl_easy_cleanup( curl ); } curl_global_cleanup(); std::cout << result << "\n\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 (as a char) cin >> input; //check is actually a char if (cin.fail()) { //more recursion, could cause issues, could you find another way? cout << "Invalid character, try again!" << endl; CheckPlayerInput(); } //converts char to upper case input = toupper(input); //check the input character // maps the input keys to the grid reference //calling the FillSquare method switch (input) { case '1': FillSquare(0, 0); break; //top-left case '2': FillSquare(0, 1); break; //top-centre case '3': FillSquare(0, 2); break; //top-right case '4': FillSquare(1, 0); break; //middle-left case '5': FillSquare(1, 1); break; //middle-centre case '6': FillSquare(1, 2); break; //middle-right case '7': FillSquare(2, 0); break; //bottom-left case '8': FillSquare(2, 1); break; //bottom-centre case '9': FillSquare(2, 2); break; //bottom-right //IF NOT ANY OF THE ABOVE default: { //more recursion, could cause issues // cout << "Invalid character, try again!" << endl; CheckPlayerInput(); } break; } }
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 character, try again!" << endl; invalid = true; } break; } } while(invalid); } The while loop will repeat as long as the input is 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 better way to write an optional vector of strings as a parameter?
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"})); func();
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 T m_val; virtual T getValue() {return m_val}; // trivial, but potentially complicated computation in derived classes // will come into play below template <typename U, typename V> struct LogicalAnd; }; And the value of T that any instance holds is accessed by getValue(). The types I am interested in are primarily arithmetic data types, and the use case for this class will be that its value can be accessed by getValue(), but also that I could define an arbitrary derived class MyValue<T> later down the road that could perform some heavy computation to store & return different values throughout the runtime of the program. Given that, I'd like to be able to "book" operations, e.g. &&, between two instances to reflect their lazily-updated values. A straightforward implementation of operator overloading does not achieve this, since it will return the basic data type value as evaluated at that line: // overload && operator template <typename U, typename V> bool operator&&(Value<U>& a, Value<V>& b) { return (a && b); } // returns a basic data type bool evaluated at above line. X So, I instead can write a proxy class representing the operation that I want and overload the operator such that it returns an instance of the proxy. // addition of two existing Value template <typename T> template <typename U, V> struct Value<T>::LogicalAnd { virtual T getValue() override { return m_valA->getValue() && m_valB->getValue(); } Value<U>* m_valA; Value<V>* m_valB; }; // overload && operator template <typename U, typename V> auto operator&&(Value<U>& a, Value<V>& b) { return typename Value<decltype(a.m_val && b.m_val)>::template LogicalAnd<U,V>{&a, &b}; } // returns a Value<X>::LogicalAnd<U,V>, X is most likely bool. Then, I can get the lazy evaluation I want by calling getValue() of this proxy instance: Value<double> a{1.0}; Value<int> b{0.0}; c = a&&b; // c is Value<bool>::LogicalAnd<double,int> c.getValue(); // = false b.m_val = 1.0; // update the value of b c.getValue(); // = true!!! The question is regards to whether this would still be considered losing short-circuit behaviour of the operation. As I see it, it should be at least effectively preserved, as the built-in && operator is being used by LogicalAnd implementation and heavy computation is done on-the-fly by the operands' getValue() methods. In other words, whenever I call c.getValue(), if a.getValue() is already false, then b.getValue() would not be called. Would a use case such as this warrant a "good-enough" practice for overloading these operators?
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 second operand could be *p where p was initialized as Value<int> * p = nullptr. Do you want to evaluate *nullptr?) As I see it, it should be at least effectively preserved, You do get the majority of the performance benefit in your scenario, yes. I'd be wary of calling it "short-circuiting" though (at least without additional qualification), as others would likely misunderstand the intent and infer more than you intend. Would a use case such as this warrant a "good-enough" practice for overloading these operators? First of all, this question is tangential to the performance question. Whether or not you should overload && should be based more on how surprising the behavior is to programmers than on how efficient the implementation is. See point 1 of The Three Basic Rules of Operator Overloading in C++. In this respect, I would be surprised to have operator&& return an object that has to be again tested to get a boolean value. So I would go with: no, this is not a good way to overload the operator. A better approach would be to define a named function that returns this proxy. Also, perhaps instead of having to call a function to evaluate the proxy as a bool, the proxy could define a user-defined conversion function? Another consideration is over-engineering. You've written an auxiliary template and changed how operator&& is used; for what benefit? Your stated justification is "I can get the lazy evaluation I want by calling getValue() of this proxy instance". However, you can get the exact same functionality without the overhead of a proxy. You just need to make your original operator&& non-recursive. // overload && operator template <typename U, typename V> bool operator&&(Value<U>& a, Value<V>& b) { return a.getValue() && b.getValue(); // CHANGE: Call getValue to avoid recursion } int main() { Value<double> a{1.0}; Value<int> b{0}; // CHANGE: initialize with an integer std::cout << (a&&b) << '\n'; // 0 means false b.m_val = 1; // update the value of b std::cout << (a&&b) << '\n'; // 1 means true!!! } There might be a reason for your proxy in your full code, but there is no reason to introduce it for this question. You've made the question more complex than necessary, hence less accessible to those who might benefit from it. With the proxy or without, the result is the evaluation of a.getValue() && b.getValue() at the given line. When getValue() returns a type for which operator&& is not overridden, the result is bool and b.getValue() is invoked only when a.getValue() evaluates to truth. If getValue() returns a type for which operator&& is overridden, then the result might be something other than bool, but at the same time you lose the short-circuiting you've been striving for. So ignore this case? If you need to handle this case, just change the return type in the operator&& template from bool to auto. Exact same end result as your approach with a proxy, but with more familiar syntax and less typing. As far as this question goes, your approach is over-engineered. So, no, it is not good practice for overloading.
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]; void send2(string in) { WSADATA wsa; memset(&wsa, 0, sizeof(wsa)); int error = WSAStartup(MAKEWORD(2, 2), &wsa); SOCKET btSocket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); SOCKADDR_BTH sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.addressFamily = AF_BTH; sockAddr.serviceClassId = RFCOMM_PROTOCOL_UUID; sockAddr.port = BT_PORT_ANY; BTH_ADDR tmpaddr = 0; sscanf_s("7C:9E:BD:4C:BF:B2", "%02x:%02x:%02x:%02x:%02x:%02x", &aaddr[0], &aaddr[1], &aaddr[2], &aaddr[3], &aaddr[4], &aaddr[5]); *&sockAddr.btAddr = 0; for (i = 0; i < 6; i++) { tmpaddr = (BTH_ADDR)(aaddr[i] & 0xff); *&sockAddr.btAddr = ((*&sockAddr.btAddr) << 8) + tmpaddr; } connect(btSocket, (SOCKADDR*)&sockAddr, sizeof(sockAddr)); char charIn[28]; strcpy_s(charIn, in.c_str()); send(btSocket, charIn, (int)strlen(charIn), 0); closesocket(btSocket); } void recv2() { WSADATA wsa; memset(&wsa, 0, sizeof(wsa)); int error = WSAStartup(MAKEWORD(2, 2), &wsa); SOCKET btSocket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); SOCKADDR_BTH sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.addressFamily = AF_BTH; sockAddr.serviceClassId = RFCOMM_PROTOCOL_UUID; sockAddr.port = BT_PORT_ANY; BTH_ADDR tmpaddr = 0; sscanf_s("7C:9E:BD:4C:BF:B2", "%02x:%02x:%02x:%02x:%02x:%02x", &aaddr[0], &aaddr[1], &aaddr[2], &aaddr[3], &aaddr[4], &aaddr[5]); *&sockAddr.btAddr = 0; for (i = 0; i < 6; i++) { tmpaddr = (BTH_ADDR)(aaddr[i] & 0xff); *&sockAddr.btAddr = ((*&sockAddr.btAddr) << 8) + tmpaddr; } connect(btSocket, (SOCKADDR*)&sockAddr, sizeof(sockAddr)); const int outLen = 1; char charOut[outLen]; recv(btSocket, charOut, outLen, 0); cout << charOut; closesocket(btSocket); cout << WSAGetLastError(); } int main() { recv2(); }
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(), (int)in.size(), 0); In any case, your garbage issue is because you are not sending a null terminator after the sent data, and you are not null-terminating the buffer you are reading into, but you are displaying the buffer as if it were null-terminated. You need to pay attention to the return value of recv() and display only as many bytes as you actually receive, eg: const int outLen = 1; char charOut[outLen+1]; int numBytes = recv(btSocket, charOut, outLen, 0); if (numBytes > 0) { charOut[numBytes] = '\0'; cout << charOut; } Or: const int outLen = 1; char charOut[outLen]; int numBytes = recv(btSocket, charOut, outLen, 0); if (numBytes > 0) { cout.write(charOut, numBytes); }
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 manually with other functions such as addstr() in for loops?
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 deletion? If not, How can I achieve what I want?
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() { std::cout << "ns::test" << std::endl; } } struct cl { static void test() { std::cout << "cl::test" << std::endl; } }; void func() { std::cout << "func" << std::endl; } int main() { ns::test(); cl::test(); func(); return 0; } I saved that as test.cpp, compiled it with g++ test.cpp -o test, then started it inside GDB: $ gdb test GNU gdb (GDB) 11.1 [...] Reading symbols from test... (No debugging symbols found in test) (gdb) start Calling func from GDB works as expected: (gdb) call (void)func() func The others, however, do not: (gdb) call (void)ns::test() No symbol "ns" in current context. (gdb) call (void)cl::test() No symbol "cl" in current context. It works fine if it was compiled with -ggdb, but that's not usually an option if the source code is unavailable. It's worth pointing out that GDB is aware of these functions and their addresses: (gdb) info functions ... 0x0000000000001169 ns::test() 0x000000000000119b func() 0x000000000000124e cl::test() ... (gdb) info symbol 0x1169 ns::test() in section .text (gdb) break cl::test() Breakpoint 1 at 0x1252 Those names will also autocomplete if I press Tab, even in a call command, meaning in that case it will autocomplete to something that doesn't work. In addition, calling those functions works fine if I use their raw names: (gdb) call (void)_ZN2ns4testEv() ns::test (gdb) call (void)_ZN2cl4testEv() cl::test So what's the deal here? Is this a bug in GDB, or is there some kind of special syntax I'm unaware of?
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 }, { "chassicId": 1001, "wheelbase": 102 } ] } This is the write function. What I have tried is to parse the Json file to the QJsonArray, then iterates and map with the function id parameter in order to update the wheelbase value. void updateWheelbase(const int& id) { updatedWheelbase = dialog.wheelbaseInput().toDouble(); QFile file("json file path"); file.open(QIODevice::ReadOnly | QIODevice::Text); QByteArray jsonData = file.readAll(); file.close(); QJsonDocument itemDoc = QJsonDocument::fromJson(jsonData); QJsonObject rootObject = itemDoc.object(); QJsonArray valuesArray = rootObject.value("$values").toArray(); //get a copy of the QJsonObject QJsonObject obj; for (auto v: valuesArray) { QJsonObject o = v.toObject(); if (o.value("chassicId").toInt() == id) { obj = o; break; } } // modify the object obj["wheelbase"] = updatedWheelbase; int position = 0; // erase the old instance of the object for (auto it = valuesArray.begin(); it != valuesArray.end(); ++it) { QJsonObject obj = (*it).toObject(); if (obj.value("chassicId").toInt() == id) { valuesArray.erase(it); //assign the array copy which has the object deleted rootObject["$value"] = valuesArray; break; } position++; } // add the modified QJsonObject valuesArray.append(obj); // replace the original array with the array containing our modified threshold object itemDoc.setObject(rootObject); file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate); file.write(itemDoc.toJson()); file.close(); }
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 <QJsonArray> void updateWheelbase() { int id = 1001; double updatedWheelbase = 1.1; QFile file("./Debug/a.json"); file.open(QIODevice::ReadOnly | QIODevice::Text); QByteArray jsonData = file.readAll(); file.close(); QJsonDocument itemDoc = QJsonDocument::fromJson(jsonData); QJsonObject rootObject = itemDoc.object(); QJsonArray valuesArray = rootObject.value("$values").toArray(); //get a copy of the QJsonObject QJsonObject obj; for (auto v : valuesArray) { QJsonObject o = v.toObject(); if (o.value("chassicId").toInt() == id) { obj = o; break; } } // modify the object obj["wheelbase"] = updatedWheelbase; int position = 0; // erase the old instance of the object for (auto it = valuesArray.begin(); it != valuesArray.end(); ++it) { QJsonObject obj = (*it).toObject(); if (obj.value("chassicId").toInt() == id) { valuesArray.erase(it); //assign the array copy which has the object deleted rootObject["$values"] = valuesArray; break; } position++; } // add the modified QJsonObject valuesArray.append(obj); rootObject["$values"] = valuesArray; // replace the original array with the array containing our modified threshold object itemDoc.setObject(rootObject); file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate); file.write(itemDoc.toJson()); file.close(); } int main(int argc, char *argv[]) { QApplication a(argc, argv); updateWheelbase(); return a.exec(); }
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)) Is there a way to use the underlying hash function without the overhead of creating and destroying a string object, and without implementing an explicit hash algorithm (probably worse than the standard one)? EDIT: I was thinking of something like a generic hash specialization taking a couple of iterators, but it does not seem to exist.
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 more about array of structure, please check following resources Array of Structures vs. Array within a Structure in C/C++ C Array of Structures Array of Structures in C
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 the compiler of cause gets angry (makes sense container.size() is not static). Is there are way to get around this? I don't know the size of the container in advance and I will never know it :( template<typename T> bool valid_container_type(const T& container) { (void) container; if constexpr (std::is_same<T, std::vector<uint8_t>>::value) { return true; } else if constexpr (std::is_same<T, std::vector<char>>::value) { return true; } else if constexpr (std::is_same<T, std::array<char, container.size()>>::value) { return true; } else if constexpr (std::is_same<T, std::array<uint8_t, container.size()>>::value) { return true; } else if constexpr (std::is_same<T, std::string>::value) { return true; } return false; }
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_array_size<std::array<T, S>> { constexpr static size_t size = S; }; Then use it as: if constexpr (std::is_same<T, std::array<uint8_t, get_array_size<T>::size>>::value) Note that you have to move the if branch for std::string before the one before std::array. Otherwise you need to define size (and give it a default value) in the primary template too.
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 { return _actor->action(); // This returns a different type :( // What to do here ??? ^ } catch (ConnectionError const& e) { return std::make_ready_future<Result>(Result::ConnectionError); } catch (ServerError const& e) { return std::make_ready_future<Result>(Result::ServerError); } } so essentially the library doesn't have specific return codes for error cases, they are rather emitted as exceptions. Handling that is easy because I can construct ready futures with the appropriate value. The problem (ironically) is with the non exceptional path, where the library's std::future<bool> has to be transformed to std::future<Result>. It's pointless to .get() the result and construct a ready future based on its value (true -> Ok, false -> Failed) because this way I'm removing asynchronicity from my function. Is there a better way to handle this?
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; } } catch (ConnectionError const& e) { return Result::ConnectionError; } catch (ServerError const& e) { return Result::ServerError; } }); }
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? When should I be using static const/constexpr member variables? Why are constexpr member variables not allowed? #include <iostream> class Foo { private: int var {92}; public: void bar() { char chr {var}; std::cout << chr << '\n'; } }; int main() { Foo foo; foo.bar(); }
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 the target type If you declare var as static const/constexpr, it becomes a constant expression and the value 92 could be stored in char, then the code works fine.
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_slist_append(headers, "Accept:"); headers = curl_slist_append(headers, "Authorization: ABCDC0F725997BEF3C6B90B0E39D9C314DCB58553FA47CD3598BBB8910A8CE6E"); headers = curl_slist_append(headers, "Host: localhost"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); //Updating the header like this auto *test = headers; while (test != NULL) { if (strstr(test->data, "Authorization:")) { strcpy_s(test->data, strlen("Authorization: A5484526D0F7A671ABCD0C091755532A63475719E460ED6A807C4AAD70BCEDA0") + 1, "Authorization: A5484526D0F7A671CE400C091755532A63475719E460ED6A807C4AAD70BCEDA0"); break; } test = test->next; }
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_MAJOR != 7 || LIBCURL_VERSION_MINOR != 79 || LIBCURL_VERSION_PATCH != 1 # error "libcurl version is is changed. Be sure Curl_slist_duplicate is not changed in lib/slist.h" #endif struct curl_slist *Curl_slist_duplicate(struct curl_slist *inlist); struct curl_slist* headers = nullptr; struct curl_slist* commonheaders = nullptr; commonheaders = curl_slist_append(commonheaders, "Accept:"); commonheaders = curl_slist_append(commonheaders, "Host: localhost"); // Update the headers. curl_slist_free_all(headers); headers = Curl_slist_duplicate(commonheaders); headers = curl_slist_append(headers, "Authorization: ABCDC0F725997BEF3C6B90B0E39D9C314DCB58553FA47CD3598BBB8910A8CE6E"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); Or #include <curl/curl.h> struct curl_slist* headers = nullptr; struct curl_slist* headers = nullptr; headers = curl_slist_append(headers, "Accept:"); headers = curl_slist_append(headers, "Host: localhost"); headers = curl_slist_append(headers, "Authorization: ABCDC0F725997BEF3C6B90B0E39D9C314DCB58553FA47CD3598BBB8910A8CE6E"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); // Remove the last header. curl_slist* h = headers; for (curl_slist* next = h->next; next->next; h = next->next, next = h->next) {} curl_slist_free_all(h->next); h->next = nullptr; // Append new header. headers = curl_slist_append(headers, "Authorization: ABCDC0F725997BEF3C6B90B0E39D9C314DCB58553FA47CD3598BBB8910A8CE6E"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
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 class that uses this concept to handle object_one with various traits (for example, half of Source classes returns object_one): template <concepts::Traits _Traits> class Object_one_handler final { static std::string handle_object(const object_one& obj) {/*...*/} }; Then I have Objects_handlers concept of handlers for various objects from set {object_one, object_two, object_three} from various Sources with their Traits: template<template <concepts::Traits _Traits> class _Objects_handlers, typename _Object> concept Objects_handlers = requires(const _Object& obj) { // has handle_object method { _Objects_handlers<???????>::handle_object(obj) } -> std::same_as<std::string>; }; Finally, I creating some database with specified as template parameter Object_handler: template<concepts::Objects_handlers _handler> class database {...}; (Actually all of concepts have additional requirements, but it doesn't matter here) So problem is in last Objects_handlers concept: template<template <concepts::Traits _Traits> class _Objects_handlers, typename _Object> concept Objects_handlers = requires(const _Object& obj) { // has handle_object method { _Objects_handlers<???????>::handle_object(obj) } -> std::same_as<std::string>; ^^^^^^^ }; I can't check _Objects_handlers method without template parameter (obviously) and I can't properly set the template parameter which must be one of Traits. How can I do that? And actually it may be problem in usage of Objects_handlers in template of database class, so one more question: how to use it? P.S. It can be XY problem or not about concepts at all... Maybe composition with strategy pattern will be more usefull, but still want try to create this maybe useless, but workable concept.
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) { z.f(); }; The problem is - class templates in C++ just don't work like this. Even for a particular class template, like C, you can't require that every specialization has f. There's no way to ensure that like somebody, somewhere, didn't add: template <> struct C<std::vector<std::list<std::deque<int>>>> { }; All you can do is check that a specific type has a nullary member function named f. And that's: template <typename T> concept HasF = requires (T t) { t.f(); }; The type-constraint syntax, template <Concept T>, is only available for concepts that constrain types, not concepts that constrain templates or values.
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 "databasehandler.h" #include "global_objects.hpp" #include <QNetworkRequest> #include <QDebug> #include <QJsonDocument> #include <QVariantMap> #include <iostream> DatabaseHandler::DatabaseHandler(QObject *parent) : QObject(parent) { m_networkManager = new QNetworkAccessManager ( this ); QVariantMap newUser; newUser[ "Stress" ] = QString::number(stressed); newUser[ "Sleep" ] = QString::number(tired); newUser[ "Hungry" ] = QString::number(hungry); newUser[ "Happy" ] = QString::number(happy); newUser[ "Grade" ] = QString::number(grade); newUser[ "Date" ] = "1/10/21"; newUser[ "Gender" ] = QString::number(gender); newUser[ "Aid" ] = QString::number(help); QJsonDocument jsonDoc = QJsonDocument::fromVariant( newUser ); QNetworkRequest newUserRequest( QUrl( "url.json")); newUserRequest.setHeader( QNetworkRequest::ContentTypeHeader, QString( "application/json" )); m_networkManager->post( newUserRequest, jsonDoc.toJson() ); } DatabaseHandler::~DatabaseHandler() { m_networkManager->deleteLater(); } void DatabaseHandler::networkReplyReadyRead() { qDebug() << m_networkReply->readAll(); } Global objects .hpp: #define GLOBAL_OBJECTS_HPP extern int happy; extern int happy; extern int hungry; extern int tired; extern int stressed; extern int gender; extern bool help; extern int grade; #endif // GLOBAL_OBJECTS_HPP global objects .cpp: namespace { int happy; int hungry; int tired; int stressed; int gender; bool help; int grade; } and checkinapp.cpp: #include "checkinapp.h" #include "ui_checkinapp.h" #include "databasehandler.h" #include "global_objects.hpp" #include <QNetworkRequest> #include <QDebug> #include <QJsonDocument> #include <QVariantMap> #include <iostream> using namespace std; checkinapp::checkinapp(QWidget *parent) : QMainWindow(parent), ui(new Ui::checkinapp) { ui->setupUi(this); } checkinapp::~checkinapp() { if(help == 0) { delete ui; } if(help == 1) { cout << "help"; } } void checkinapp::on_happy_valueChanged(int value) { happy = value; } void checkinapp::on_hungry_valueChanged(int value) { hungry = value; } void checkinapp::on_sleep_valueChanged(int value) { tired = value; } void checkinapp::on_stress_valueChanged(int value) { stressed = value; } void checkinapp::on_male_toggled(bool checked) { if(checked == true) { gender = 0; } } void checkinapp::on_female_toggled(bool checked) { if(checked == true) { gender = 1; } } void checkinapp::on_other_toggled(bool checked) { if(checked == true) { gender = 2; } } void checkinapp::on_help_toggled(bool checked) { if(checked == true) { help = 1; } } The error says the following: error photo .pro file: QT += network greaterThan(QT_MAJOR_VERSION, 4): QT += widgets CONFIG += c++11 console # You can make your code fail to compile if it uses deprecated APIs. # In order to do so, uncomment the following line. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 SOURCES += \ databasehandler.cpp \ global_objects.cpp \ main.cpp \ checkinapp.cpp HEADERS += \ checkinapp.h \ databasehandler.h \ global_objects.hpp FORMS += \ checkinapp.ui # Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += target
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); } int main(){ std::vector<string> vstr{"vector", "In", "this", "example", "am", "supposed", "sort", "a", "of", "I", "strings", "depending"}; std::string::size_type len = 5; // std::sort( vstr.begin(), vstr.end(), // std::bind(is_shorter, placeholders::_1, len) ); std::sort( vstr.begin(), vstr.end(), std::bind( [](std::string const& str, std::string::size_type sz){ return !(str.size() < sz);}, std::placeholders::_1, len ) ); for(auto const& str : vstr) std::cout << str << ", "; std::cout << '\n'; std::cout << '\n'; } The output: depending, strings, supposed, example, vector, In, this, am, sort, a, of, I, As you can see the program works fine as I expected but what matters and confuses me is how come the comparison operation: Inside sort I guess something like this: comp(*it, *it + 1); // for simplicity sake only. (I mean two elements of the same sequence -of course same type- are passed-in) Which I mean the comparison operation is a binary operation that is called each iteration for each contiguous elements. Those elements are of the same type (of the elements in the sequence). So how can std::bind changes the second parameter to std::string::size_type rather than std::string? How can std::bind makes the operation takes only one string? and what happens to the second string passed in? Can someone explain to me what happens exactly in std::bind here? It doesn't matter me if the lambda passed-in or the custom comparison operation if it takes arguments of the same type: for example to sort a vector of strings so that the elements that are equal to a given string appear first: std::sort(vstr.begin(), vstr.end(), std::bind([](std::string s1, std::string s2 ){ return s1 == s2;}, _1, std::string("vector") )); Now If I run the program I get the word "vector" appearing first at the beginning.
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::bind, it copies/moves all of the additional arguments provided into the returned data structure. This structure has a templated operator(). The parameters passed to operator() are substituted in place of the std::placeholders objects that were provided during the call to bind. The important part here is that any parameters passed during the invocation that are not mentioned are not forwarded to the bound functor. So in this case, because you didn't pass std::placeholders:_2 to the call to bind, the second argument is discarded. The second argument to the lambda is filled in by len which you passed in. There is more functionality in std::bind, but this covers the simplest use case.
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_stdin[2]; int p_stdout[2]; int pid; if (pipe(p_stdin) == -1) return -1; if (pipe(p_stdout) == -1) { close(p_stdin[0]); close(p_stdin[1]); return -1; } pid = fork(); if (pid < 0) { close(p_stdin[0]); close(p_stdin[1]); close(p_stdout[0]); close(p_stdout[1]); return pid; } else if (pid == 0) { close(p_stdin[1]); dup2(p_stdin[0], 0); close(p_stdout[0]); dup2(p_stdout[1], 1); dup2(::open("/dev/null", O_RDONLY), 2); /// Close all other descriptors for the safety sake. for (int i = 3; i < 4096; ++i) ::close(i); setsid(); execl("/bin/sh", "sh", "-c", command, NULL); _exit(1); } close(p_stdin[0]); close(p_stdout[1]); return pid; } Then, I am using the kill function, to pause, resume and stop the process but it does not work as I expected. Here is an example: int main() { // The process prints on file allowing me to figure out whether the process is paused / stopped, or is running const char * command = "for i in {1..1000}; do echo $i >> /Users/remi/test/data.txt; sleep 1s;done"; // Run the command and record pid auto pid = system2(command); std::cout << "pid = " << pid << "\n"; // with this pid, I could ensure that `ps -p <pid>` returns the correct command std::cout << "process should be running!\n"; // It is! // wait std::this_thread::sleep_for(std::chrono::seconds(10)); // pause kill(pid, SIGTSTP); std::cout << "process should be paused!\n"; // But it is not! // wait std::this_thread::sleep_for(std::chrono::seconds(10)); // resume process kill(pid, SIGCONT); std::cout << "process should be running!\n"; // Sure, it is as it has never been stopped // wait std::this_thread::sleep_for(std::chrono::seconds(10)); // Kill process kill(pid, SIGSTOP); std::cout << "process should be stopped!\n"; // That worked! // wait std::this_thread::sleep_for(std::chrono::seconds(10)); } Can you please help me figure out how to fix this code to ensure the process stops and resume as I was expected. FYI, I am on a macOS and wish the solution work on any POSIX system.
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> { zz_type_gen(): zz<T>() {} }; zz<int> _oi; zz_type_gen<char> _od; }; Compiling with g++ 11, clang++ 12 and cl.exe with -std=c++20 works fine but if foo template argument is removed in line with // ERROR comment compilation fails. This seems to indicate that zz name is looked up first in global namespace inside nested class in case nested class (own_type) is not template. However zz name is looked up first in class foo in case nested class is template (zz_type_gen). I could not find clear explanation on how C++ names lookup works, but intuitively this seems inconsistent.
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 also used to declare or inherit constructors). To prevent (specializations of) dependent base classes from shadowing names used in templated classes, unqualified name lookup is performed immediately in the template definition and ignores such bases entirely. This has the odd interaction with the injected-class-name model that even a name that would obviously refer to the base in each instantiation is sought outside the class instead. This does provide consistency with the case where the dependent base is more complicated than a template-id that names some specialization of a particular class template. Therefore, own_type finds the injected-class-name of its base, which can be used either as a type-name (by omitting <foo, double>) or as the template-name that ::z is. zz_type_gen, however, finds foo::zz; it could use typename zz_type_gen::zz to find the injected-class-name instead of repeating the template argument list. (C++20 dispenses with the requirement for typename in some contexts but not others; a mem-initializer still requires it, but that was likely an oversight.)
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 value": Am I missing something? I am using the latest Microsoft Visual Studio 2019 version: 16.11.4, and the reference (https://en.cppreference.com/w/cpp/compiler_support) states that constexpr strings and vectors are supported by this compiler version: I have also tried the constexpr std::array, which does work. Could the issue have anything to do with the dynamic memory allocation associated with vectors?
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::vector<int> v = {1, 2, 3}; } Because v's allocation persists - it is non-transient. That's what the error is telling you: <source>(6): error C2131: expression did not evaluate to a constant <source>(6): note: (sub-)object points to memory which was heap allocated during constant evaluation v can't be constant because it's still holding on to heap allocation, and it's not allowed to do so. But you can write this: constexpr int f() { std::vector<int> v = {1, 2, 3}; return v.size(); } static_assert(f() == 3); Here, v's allocation is transient - the memory is deallocated when f() returns. But we can still use a std::vector during constexpr time.
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 returns: true Substituting b with the literal 4 returns: false INT32_MIN is defined in stdint.h as the literal: (-2147483647i32 - 1). What in the '<' operation occurs for this overflow error? It acts intuitively when b is type cast to int. Another note, adding the following indicates no overflow error. std::cout << sizeof(size_t) << std::endl; std::cout << sizeof(int) << std::endl; Outputs: 4 4 According to https://en.cppreference.com/w/cpp/types/size_t , size_t is unsigned. According to https://en.cppreference.com/w/cpp/language/operator_comparison , the < operator causes conversion to the invoking type on the left hand side. What occurs in the conversion between this literal (integer type?) and size_t for it to become equal to 2147483648?
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://www.electronics-tutorials.ws/binary/signed-binary-numbers.html#:~:text=We%20have%20seen%20that%20negative,MSB)%20as%20a%20sign%20bit.&text=The%20representation%20of%20a%20signed,then%20the%20number%20is%20negative.
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::FindResourceOrThrow( "model/model.urdf"); drake::multibody::Parser parser(&plant_, &scene_graph); parser.AddModelFromFile(full_name); plant_.Finalize(); return 1; } The above code give me the following error: terminate called after throwing an instance of 'std::runtime_error' what(): Drake resource_path 'model/model.urdf' does not start with drake/. Aborted (core dumped) My Directory layout is: Project Folder model urdf src main.cpp CmakeLists.txt my src CmakeLists.txt is: cmake_minimum_required(VERSION 3.16.3) list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}") message("CMAKE Directory : " ${PROJECT_SOURCE_DIR}) project(IK VERSION 1.0) # specify the C++ standard set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED True) find_package (Eigen3 3.3 REQUIRED NO_MODULE) find_package(drake CONFIG REQUIRED) # specify the main source file set(SOURCE main.cpp) add_executable(${PROJECT_NAME} ${SOURCE}) target_link_libraries("${PROJECT_NAME}" Eigen3::Eigen drake::drake} Essentially, my objective is to use a custom urdf and build a model and use it for the inverse kinematics class.
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 pass a filesystem path without calling FindResource() (or any of its variants). Whether it is an absolute or relative path will depend on where your executable ends up w.r.t. the urdf in your built/installed system.
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 << "dataFrom = " << asctime(gmtime(&dataFrom)) << "\n"; return 0; } How do i print dataFrom using gdb correctly ? I have read about informing gdb about a structure if it was user defined. But what to do with something inbuilt such as time_t ? badri@badri-All-Series:~/progs$ g++ --std=c++11 testgdb.cpp -g badri@badri-All-Series:~/progs$ gdb ./a.out GNU gdb (Ubuntu 8.1.1-0ubuntu1) 8.1.1 Copyright (C) 2018 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from ./a.out...done. (gdb) b main Breakpoint 1 at 0x903: file testgdb.cpp, line 9. (gdb) r Starting program: /home/badri/progs/a.out Breakpoint 1, main () at testgdb.cpp:9 9 { (gdb) n 10 time_t dataFrom = 1234560; (gdb) p dataFrom $1 = 93824992233952 (gdb) p *dataFrom $2 = 1447122753 (gdb) p/s dataFrom $3 = 93824992233952
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 symbols from ./a.out... (gdb) b main Breakpoint 1 at 0x11e9: file testgdb.cpp, line 9. (gdb) r Starting program: /home/user/path/a.out Breakpoint 1, main () at testgdb.cpp:9 9 { (gdb) n 10 time_t dataFrom = 1234560; (gdb) p dataFrom $1 = 0 (gdb) n 11 cout << "dataFrom = " << asctime(gmtime(&dataFrom)) << "\n"; (gdb) p dataFrom $2 = 1234560 (gdb)
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 namespace std; class Fuu{ public: Fuu(int v):m_property(v){} void setProperty(int v ){m_property = v;} std::function<void(int)> lmbSet {[=](int v){ m_property = v;}}; std::function<void(char *)> lmbGet {[=](char * v){ cout<< v << " "<< m_property << endl;}}; std::function<void()> lmb4Static {[=]{ cout<<"static: "<< s_fild << endl;}}; void call() const { lmbGet("test") ; } static int s_fild ; int m_property; }; int Fuu::s_fild = 10; int main() { Fuu obj(3); obj.call(); obj.setProperty(5); obj.call();//expect 3 obj.lmbSet(12); obj.call(); //expect 3 obj.lmb4Static(); Fuu::s_fild = 11; obj.lmb4Static(); //expect 10 return 0; }
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 copy of non-local data, you can do it using "generalized capture" syntax which was added in C++14: [m_property=m_property](char * v){ cout<< v << " "<< m_property << endl;}
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 select test1.cpp), and then you can compile the project into a runnable executable (provided the code is valid, that is).
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 used I get unqualified-id or the compiler moans about not converting to char* const*. I can get const char * easily, of course. char const * argv = "0"; compiles OK in Netbeans with C++14 but char * const * argv = "0"; produces "error: cannot convert 'const char *' to 'char * const *'" in initialisation (sic). How do you declare char* const* or am I mixing C with C++ so I'm up the wrong tree?
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 that your question is not how to declare a char* const* but how to initialize it. Due to arrays decaying to a pointer, you could declare an array of pointers (char* const argv[]) instead of a pointer to pointer (char* const * argv). See The 1D array of pointers way portion of A: 2D Pointer initialization for how to initialize such a beast. Beware: given your setup, the "2D array way" from that answer is not an option. Reminder: The last pointer in the argument vector is null; argv[argc] == nullptr when those values are provided by the system to main().
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 using memcpy in this way: #include <boost/any.hpp> #include <cstring> #include <string> #include <iostream> class Data { public: template <typename T> Data(T value) : m_value(value) {} template <typename T> T Read() const { return boost::any_cast<T>(m_value); } private: boost::any m_value; }; int main() { Data src(std::string("This is some data.")); std::cout << "Size: " << sizeof(src) << std::endl; std::cout << "SRC: " << src.Read<std::string>() << std::endl; void* dst = malloc(sizeof(src)); std::memcpy(dst, &src, sizeof(src)); const auto data = static_cast<Data*>(dst); std::cout << "DST: " << data->Read<std::string>() << std::endl; std::free(dst); } This code appears to work, and prints the following output: Size: 8 SRC: This is some data. DST: This is some data. But depending on the type stored in the Data object wouldn't the size change? No matter what type I use it always prints that the size is 8. Is this code invoking undefined behavior? If it is, how can I fix it so I can properly memcpy an object that contains a boost::any data member?
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 returned by any_cast). It is definitely not okay to memcpy the any itself, or an object containing it.
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(){ ... } #endif Then, I have other targets that link against this library. Is there a way in CMake I can detect whether bar() exists in the final libfoo.so or that this target was compiled with this option disabled? Basically, I'd like to propagate the information about how the library was compiled (e.g. with what enabled options) so I can skip downstream targets that consume it but need unsupported features.
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 bar methods" ON) add_definition_if_var (ADD_BAR) And, if ADD_BAR was set to ON, the ADD_BAR macro will be defined within your library project :) If you have many such options, you could do it all in one go: function (defining_option var description state) option (${var} "${description}" ${state}) if (${var}) add_compile_definitions (${var}) endif () endfunction () defining_option (ADD_BAR "Include the bar methods" ON) defining_option (ADD_FROB "Frobnicate" OFF)
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 there a way to embed a version string into the source code that I can look for in a core dump? Or is there some kind of hash/signature I can use to match it from a build? Or is there a better convention?
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 to use --build-id linker flag, which embeds a unique checksum into the binary. This is likely passed to the linker from g++ by default, but you can explicitly specify that flag with -Wl,--build-id as well. Linux kernel saves the page containing the NT_GNU_BUILD_ID ELF note, which allows you to Immediately identify what binary produced the core (using e.g. eu-unstrip -n --core core) and Use GDB to automatically load correct debug info. See e.g this article.
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> #include <iostream> int main() { std::array<int,6> x{}; std::cout << &x << "\n"; std::cout << x.data(); } Possible output: 0x7ffc86a62860 0x7ffc86a62860 And if yes, is this of any use? Is the following allowed? int* p = reinterpret_cast<int*>(&x); for (int i=0;i<6;++i){ std::cout << p[i]; }
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 that std::array<T, N> is standard-layout, even if T is int or something like that. All reasonable implementations of std::array<T, N> will have a single non-static data member of type T[N], no virtual functions, and at most a single inheritance chain with no virtual base classes, which would mean they would be standard-layout as long as T itself is standard-layout. Plus, even if T is not standard-layout, the compiler is not likely to insert padding at the beginning of the std::array object. So, while an assumption that a std::array<T, N> object has the same address as the first T object it contains is not portable, it is basically guaranteed in practice. And you can add a static_assert(sizeof(std::array<T, N>) == sizeof(T[N])); just to be sure that, if someone ever tries to build your code on an exotic implementation where it isn't the case, they'll know it's not supported.
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 using the template T. #include <iostream> using namespace std; template <typename T> class LinkedList { public: LinkedList() { head = NULL; tail = NULL; numNodes = 0; } ~LinkedList() { } int getLength() { return numNodes; } T getNodeValue(int value) { ListNode<T> *indexNode; indexNode = head; int i = 0; if (value < 0 || value > numNodes - 1) { throw; } while (indexNode->next != NULL) { if (i == value) { break; } indexNode = indexNode->next; i++; } return indexNode->contents; } void insertNode(ListNode<T> *newNode) { if (head == NULL) { head = newNode; tail = head; tail->next = NULL; numNodes++; return; } if (newNode->contents <= head->contents) { if (head == tail) { head = newNode; head->next = tail; } else { ListNode<T> *placeholder; placeholder = head; head = newNode; head->next = placeholder; } numNodes++; return; } if (newNode->contents > tail->contents) { if (head == tail) { tail = newNode; head->next = tail; } else { ListNode<T> *placeholder; placeholder = tail; tail = newNode; placeholder->next = tail; } numNodes++; return; } ListNode<T> *indexNode; indexNode = head; while (indexNode->next != NULL) { if (newNode->contents <= indexNode->next->contents) { newNode->next = indexNode->next; indexNode->next = newNode; numNodes++; return; } indexNode = indexNode->next; } } private: template <typename T> struct ListNode { ListNode() { next = NULL; } ListNode(T value) { contents = value; next = NULL; } T contents; ListNode<T> *next; }; ListNode<T> *head; ListNode<T> *tail; int numNodes; }; #endif
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 = NULL; } T contents; ListNode *next; }; And then just use LinkedList<T>::ListNode (or just ListNode inside the class). For instance, the members head and tail become: ListNode *head; ListNode *tail; Important: You cannot define the struct in the private section if its used in public function (e.g.: void insertNode(ListNode *newNode)). Otherwise, how are you supposed to create a ListNode to call insertNode from outside the class?
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> #include <mutex> void subProg1(int& ii, double& emod, double& prat); using namespace std; int main() { int imax = 4; int ii; double emod[4]; double prat[4]; std::thread threadpointer[4]; emod[0] = 10; emod[1] = 20; emod[2] = 30; emod[3] = 40; prat[0] = 0.1; prat[1] = 0.2; prat[2] = 0.3; prat[3] = 0.4; for (ii=0;ii<imax;ii++) { cout<<" In main Program " <<endl; cout<<" count = : "<<ii<<" emod = : "<<emod[ii]<<" pRat = : "<<prat[ii]<<endl; threadpointer[ii] = std::thread(subProg1,ref(ii),ref(emod[ii]),ref(prat[ii])); //threadpointer[ii].join(); } for (ii=0;ii<imax;ii++) { threadpointer[ii].join(); } } void subProg1(int& ii, double& emod, double& prat) { cout <<" In SubProgram "<<endl; cout<<" count = : "<<ii<<" emod = : "<<emod<<" pRat = : "<<prat<<endl; } The output of this run is as follows In main Program count = : 0 emod = : 10 pRat = : 0.1 In SubProgram In main Program count = : 1 emod = : count = : 1 emod = : 20 pRat = : 0.2 10 pRat = : 0.1 In SubProgram In main Program count = : 2 emod = : 20 pRat = : 0.2 count = : 2 emod = : 30 pRat = : 0.3 In SubProgram In main Program count = : 3 emod = : 40 pRat = : 0.4 count = : 3 emod = : 30 pRat = : In SubProgram count = : 2 emod = : 40 pRat = : 0.4 0.3 I do understand the calls will be out of sync. However the index and the values of emod and prat corresponding to that index don't match either. The correct values should be count = :0 emod = : 10 pRat = :0.1 count = :1 emod = : 20 pRat = :0.2 count = :2 emod = : 30 pRat = :0.3 count = :3 emod = : 40 pRat = :0.4 Wondering what I am missing. Any help is appreciated
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 seem like a proper behavior, but I cannot understand why it happens (and I actually had code where this was not what I expected). From Overload resolution: If any candidate is a function template, its specializations are generated using template argument deduction, and such specializations are treated just like non-template functions except where specified otherwise in the tie-breaker rules. OK, let's generate specializations. For #1 it's easy, it becomes int foo(int& x). For #2 special deduction rules apply, since it is a forwarding reference. i is an lvalue, thus T is deduced as int& and T&& becomes int& &&, which after reference collapsing becomes just int&, yielding the result int foo(int& x). Which is exactly the same as for #1! So I'd expect to see an ambiguous call, which does not happen. Could anyone please explain why? What tie-breaker is used to pick the best viable function here? See also the related discussion in Slack, which has some thoughts.
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 intentionally to (a) make universal references work, while (b) allowing you to overload on lvalue references if you want to handle them seperately. The tie breaker comes from the template function overload "more specialized" ordering rules. The same reason why T* is preferred over T for pointers, even though both T=Foo* and T=Foo give the same function parameters. A secondary ordering on template parameters occurs, and the fact that T can emulate T* means T* is more specialized (or rather not not, the wording in the standard is awkward). An extra rule stating that T& beats T&& for lvalues is in the same section.
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 so more dynamically based on a supplied type. As things stand, I've written a templated As() member function, but it's error-checking is clunky. Specifically, using static assert requires an unwieldy test condition. Here's a simplified version: template <typename T> T As() { if constexpr (std::is_same_v<T,int>) return AsInt(); if constexpr (std::is_same_v<T,double>) return AsDouble(); ... if constexpr (std::is_same_v<T,std::string>) return AsString(); static_assert( std::is_same_v<T,int> || std::is_same_v<T,double> || ... || std::is_same_v<T,std::string>, "Invalid template type for As()" ); } Is there a simpler way to trigger the static assert (or equivalent) if all of the conditions fail?
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 constexpr (std::is_same_v<T,double>) { return AsDouble(); } ... else if constexpr (std::is_same_v<T,std::string>) { return AsString(); } else { // this is still constexpr, so it will be discarded if any other branch was taken static_assert(dependent_false<T>::value, "invalid template type for As()"); } where dependent_false is defined as: template <class T> struct dependent_false : std::false_type {};
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_debug.is_new_data_available()) { uint32_t uuid = data_debug.get_ID(); uuidData[uuid] = { millis(), data_debug.get_data1(), data_debug.get_data2(), data_debug.get_state(), data_debug.get_temperature(), data_debug.get_battery_level(), data_debug.get_RSSI() }; } } This works, but when I get data with an existing UUID, my intuition is that the old struct never gets deleted and will eventually leak. I had an alternative code (2) below that tried to bypass this, but when the UUID was duplicated, the struct was filled with garbage. Is the code in (1) leaking or c++ automatically frees the space when the struct is no longer needed? (I know this sounds like garbage collection, but i have no idea how c++ handle structs) (2) if(uuidData.count(uuid)){ uuidData[uuid].time = millis(); uuidData[uuid].ch0 = data_debug.get_data1(); uuidData[uuid].ch1 = data_debug.get_data2(); uuidData[uuid].state = data_debug.get_state(); uuidData[uuid].temp = data_debug.get_temperature(); uuidData[uuid].vbat = data_debug.get_battery_level(); uuidData[uuid].time = data_debug.get_RSSI(); } else{ uuidData[uuid] = { millis(), data_debug.get_data1(), data_debug.get_data2(), data_debug.get_state(), data_debug.get_temperature(), data_debug.get_battery_level(), data_debug.get_RSSI() }; }
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(), data_debug.get_RSSI() }; The { millis(), data_debug.get_data1(), data_debug.get_data2(), data_debug.get_state(), data_debug.get_temperature(), data_debug.get_battery_level(), data_debug.get_RSSI() }; creates and initializes a temporary dataStruct variable, an automatic variable that will only exist until it's no longer needed. When the expression ends, the temporary goes out of scope and is destroyed. uuidData[uuid] looks in uuidData for a key that matches uuid. If it does not find one, it creates an empty dataStruct and maps it to the key. This new dataStruct is managed by uuidData. Where it comes from and where it goes is not your concern. Once a dataStruct mapped to uuid exists, a reference to it is returned. Now we have a reference to an existing dataStruct in the map and the temporary dataStruct. The = simply copies the contents of the temporary on the right into the the object represented by the reference on the left. Whatever was in the object on the left is overwritten but the object is still there and still managed by uuidData. It will be properly destroyed and deallocated when it is either removed from uuidData or uuidData goes out of scope. The temporary is destroyed automatically (ergo the name Automatic variable) for you when the expression is complete. There is no possibility for a leak here.
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++ (without using JSI). Specifically, I noticed that from react-native-builder-bob it is possible to easily start a package that bridges native modules using C++. At this point I wonder, but what does JSI introduce that is new if it was already possible to integrate JS with C++? Why should it bring performance improvements over the current solution? I apologise in advance for my lack of knowledge, but I really couldn't find the answer.
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 sharing between JS and Native threads Slow data transfer because of JSON serialisation (bottleneck) You can make the bridge to any native code Java/Konlin, ObjC/Swift, C++ etc. but you always have the problems from above. React Native JSI provides an API to the JS Runtime engine and exposes native functions and objects to JS directly - no bridge at all. It provides the following advantages: Sync call from JS thread to Native and vice-versa Fast rendering using direct call to UI Main thread Data sharing between threads You have to use C++ only to work with JSI because the JS Runtime has a C++ API but it is possible to make C++ layer between JSI and your existing Java or Swift code. JSI is the foundation for future new React Native architecture which includes: Fabric, TurboModules, CodeGen. Read more: https://github.com/react-native-community/discussions-and-proposals/issues/91
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 : list) { i.a = 5; } I already have checks in place to see what class it is, but the compiler is still not letting me access it. How can I access any field in the derived class from the base class? This question has been asked many times, but none of the methods have worked for me so far.
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 { int a; }; struct C : A { int b; }; std::list<std::unique_ptr<A>> lst; lst.push_back(std::make_unique<B>()); lst.push_back(std::make_unique<B>()); for(auto &ptr : lst) { static_cast<B*>(ptr.get())->a = 5; } Otherwise, use dynamic_cast instead to test the derived class type before accessing its fields: struct A {}; struct B : A { int a; }; struct C : A { int b; }; std::list<std::unique_ptr<A>> lst; lst.push_back(std::make_unique<B>()); lst.push_back(std::make_unique<C>()); for(auto &ptr : lst) { B *b = dynamic_cast<B*>(ptr.get()); if (b) b->a = 5; }
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 barrier with a dynamic count within ObjA, and then make ObjB aware of that barrier so that it can arrive at the barrier? I wanted to use std::barrier but I've had problems trying to do so. Thus far I cannot make a std::barrier member variable in ObjA because it requires an input size which I will only know once ObjA is constructed. If I create the barrier inside of the busy function of ObjA, then any signal function that ObjB calls to A with won't have scope to it. Is the best approach to do some homespun semaphore with busy waiting?
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 // 3) for the condition variable cv int total_count = 10; // This is count of objBs int count = total_count; void obj_b_signals() { // Do something.. bool certainCondition = true; // We have reached the condition.. if (certainCondition) { { std::lock_guard<std::mutex> lk(cv_m); count--; } std::cerr << "Notifying...\n"; cv.notify_one(); } } int main() { // obj A logic std::vector<std::thread> threads; for (size_t i=0; i<total_count; ++i) { threads.emplace_back(std::thread(obj_b_signals)); } { std::unique_lock<std::mutex> lk(cv_m); std::cerr << "Waiting for ObjBs to reach a certain condition... \n"; cv.wait(lk, []{return count == 0;}); std::cerr << "...finished waiting. count == 0\n"; } // Do something else for (std::thread & t: threads) { t.join(); } }
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-all $nf set tf[open lab1.tr w] $ns trace-all $tf proc finish{} { gobal ns nf tf $ns flush-trace close $nf close $tf exec nam prg1.nam & exit 0 } set n0[$ns node] set n1[$ns node] set n2[$ns mode] set n3[$ns node] $ns duplex-link $n0 $n2 200Mb 10ms DropTail $ns duplex-link $n1 $n2 100Mb 5ms DropTail $ns duplex-link $n2 $n3 1Mb 1000ms DropTail $ns queue-limit $n0 $n2 10 $ns queue-limit $n1 $n2 10 set udp0[new Agent/UDP] $ns attach-agent $n0 $udp0 set cbr0[new Application/Traffic/CBR] $cbr0 set packetSize_ 500 $cbr0 set interval_ 0.005 $cbr0 attach-agent $n1 $udp1 set cbr1[new Application/Traffic/CBR] $cbr1 attach-agent $udp1 set upd2[new Agent/UDP] $ns attach-agent $n2 $udp2 set cbr2[new Application/Traffic/CBR] $cbr2 attach-agent $udp2 set null0[new Agent/Null] $ns attach-agent $n3 $null0 $ns connect $udp0 $null0 $ns connect $udp1 $null0 $ns at 0.1 "$cbr0 start" $ns at 0.2 "$cbr1 start" $ns at 1.0 "finish" $ns run lab1.awk BEGIN{ c=0; } { if($1=="d") { c++; printf("%s\t%s\n",$5,$11); } } END{ printf("The no of packets dropped = %d\n",c); } Error can't read "ns_o3": no such variable while executing "set ns[new Simulator]" (file "prg1.tcl" line 1)
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 value of the given variable name. In this case, there is no variable named ns_o3, so that's your error. The rest of your program is also missing spaces before commands in [] brackets. Why did you do this?
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 std::__cxx11::basic_string<char>*}' [-Wsizeof-array-argument] size_t length = sizeof(words) / sizeof(words[0]); ^ hangman.cpp:15:47: note: declared here std::string get_random_word(std::string words[]) ^ Here is the code - #include <iostream> #include <string> #include <ctime> std::string get_random_word(std::string words[]); int main() { srand(time(0)); std::string words[] = {"cpp", "python", "java"}; std::cout << get_random_word(words); return 0; } std::string get_random_word(std::string words[]) { size_t length = sizeof(words) / sizeof(words[0]); return words[rand() % length]; }
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 length() functions for this, which are the same, and instead of using an array you can use a vector that also provides a size() function. #include <iostream> #include <string> #include <ctime> #include <vector> std::string get_random_word(std::vector<std::string>& words) { return words[rand() % words.size()]; } int main() { srand(time(0)); std::vector<std::string> words = {"cpp", "python", "java"}; std::cout << get_random_word(words); return 0; }
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 would be different. I hope the following minimal example illustrates my point: // Product function template <typename ...data_type> constexpr auto Product(data_type ..._values) { return (_values * ...); } // Static memory version template <class t_data_type, unsigned ...t_dimensions> class StaticTensor { private: std::array<t_data_type, Product(t_dimensions...)> Entries; // Store entries as contiguous memory public: StaticTensor() = default; ~StaticTensor() = default; void StaticMethod() { // Some code that operates on Entries. } }; // Dynamic memory version template <class t_data_type> class DynamicTensor { private: std::vector<t_data_type> Entries; public: DynamicTensor() = default; ~DynamicTensor() = default; template <typename ...t_dimensions> void Resize(t_dimensions ...dims) { Entries.resize(Product(dims...)); } void DynamicMethod() { // Some code that operates on Entries. } }; I have considered inheritance-based/polymorphic approaches, but it seems that I'd still have to implement separate methods in each of the specialised classes. I would ideally like all the methods to operate on the underlying iterators in std::array and std::vector, without having to worry about which data container they belong to. Can anyone suggest how I can go about doing this?
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. } }; Then your StaticTensor/DynamicTensor can inherit TensorBase to obtain the Method(). In order to enable the base class to access private members, you also need to set the base class as a friend: // Static memory version template <class t_data_type, unsigned ...t_dimensions> class StaticTensor : public TensorBase<StaticTensor<t_data_type, t_dimensions...>> { using Base = TensorBase<StaticTensor<t_data_type, t_dimensions...>>; friend Base; private: std::array<t_data_type, Product(t_dimensions...)> Entries; public: StaticTensor() = default; ~StaticTensor() = default; }; // Dynamic memory version template <class t_data_type> class DynamicTensor : public TensorBase<DynamicTensor<t_data_type>> { using Base = TensorBase<DynamicTensor<t_data_type>>; friend Base; private: std::vector<t_data_type> Entries; public: DynamicTensor() = default; ~DynamicTensor() = default; }; Demo.
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 data_type, typename ...data_types> constexpr data_type Product1(data_type _first, data_types ..._rest) // This code compiles :) { return _first*(_rest * ...); } /** Version 2. */ template <typename ...data_type> constexpr data_type Product2(data_type ..._rest) // This code does not compile :( { return (_rest * ...); }
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 function (workflow1 or workflow2) and its parameters as parameters to another general function (say, workflow)? Maybe there exist some design patterns for this kind of job? class MyClass { public: void workflow1(int x) { doThings(); // actually some code more than just one function call method1(x); doOtherThings(); // actually some code more than jus one function call } void workflow2(int x, int y=1) { doThings(); // actually some code; the same as in workflow1() method2(x,y); doOtherThings(); // actually some code; the same as in workflow1() } private: void doThings() {} void doOtherThings() {} void method1(int x) {} void method2(int x, int y) {} }; int main() { MyClass myClass; int x = 0; myClass.workflow1(x); int y = 2; myClass.workflow2(x, y); }
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::function<void()> &func) { doThings(); func(); doOtherThings(); } void doThings() {} void doOtherThings() {} void method1(int x) {} void method2(int x, int y) {} }; Or, use a pointer to member function: class MyClass { public: void workflow1(int x) { workFlowInternal(&MyClass::method1, x, 0); } void workflow2(int x, int y = 1) { workFlowInternal(&MyClass::method2, x, y); } private: void workFlowInternal(void(MyClass::* func)(int, int), int x, int y) { doThings(); (this->*func)(x,y); doOtherThings(); } void doThings() {} void doOtherThings() {} void method1(int x, int ignored=0) {} void method2(int x, int y) {} };
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) Sample input: 20101010 20101015 First code output: 4 (without line 13) Second code output: 5 (correct output) First code : #include <iostream> using namespace std; const int monthDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int countDays(int d[], int m[], int y[]) { int totalDays[2]; for (int i = 0; i < 2; i++) { totalDays[i] += d[i] + 365 * y[i]; for (int j = 0; j < m[i] - 1; j++) totalDays[i] += monthDays[j]; } totalDays[0] -= 1; if (totalDays[0] > totalDays[1]) { return totalDays[0] - totalDays[1]; } else { return totalDays[1] - totalDays[0]; } } int main() { int d[2], m[2], y[2], yyyymmdd; for(int i = 0; i < 2; i++){ cin >> yyyymmdd; d[i] = yyyymmdd % 100; m[i] = (yyyymmdd / 100) % 100; y[i] = yyyymmdd / 10000; } cout << countDays(d, m, y); return 0; } Second code : #include <iostream> using namespace std; class Solution { public: const int monthDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int countDays(int d[], int m[], int y[], int totalDays[]) { for (int i = 0; i < 2; i++) { totalDays[i] += d[i] + 365 * y[i]; for (int j = 0; j < m[i] - 1; j++) totalDays[i] += monthDays[j]; } if (totalDays[0] > totalDays[1]) { return totalDays[0] - totalDays[1]; } else { return totalDays[1] - totalDays[0]; } } }; int main() { int d[2], m[2], y[2], yyyymmdd, totalDays[2]; for(int i = 0; i < 2; i++){ cin >> yyyymmdd; d[i] = yyyymmdd % 100; m[i] = (yyyymmdd / 100) % 100; y[i] = yyyymmdd / 10000; totalDays[i] = 0; } Solution ob; cout << ob.countDays(d, m, y, totalDays); return 0; }
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 second example. Choose a new name for the parameter totalDays in the second case.
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 cast was happening. Why is this not happening?
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 c); void F(){test(1);} // OK void G(){test(10000);} // warning void H(int v){test(v);} // need -Wconversion Compiler Explorer
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 stack. But there is no error in them, I left those in the code where there may be an error. #include <cstring> #include <iostream> struct Stack { int data; int min; Stack* next; }; void Push(Stack** top, int n) { Stack* st = new Stack(); st->data = n; if (*top == NULL) { *top = st; (**top).min = n; } else { st->min = ((n <= (**top).min) ? n : (**top).min); st->next = *top; *top = st; } std::cout << "ok" << std::endl; } void Pop(Stack** top) { if (*top != NULL) { std::cout << (**top).data << std::endl; *top = (*top)->next; } else { std::cout << "error" << std::endl; } } int main() { Stack* top = nullptr; int m; std::cin >> m; std::string str; for (int i = 0; i < m; ++i) { std::cin >> str; if (str == "push") { int value; std::cin >> value; Push(&top, value); } if (str == "pop") { Pop(&top); } } delete top; }
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 (top != nullptr) {" Stack* next = top->next; // we can't use `top` after we `delete` it, save `next` beforehand delete top; top = next; } Now, about more general things. The course teaches you some really old C++ (almost just plain C; even C here is bad though). At the very least, your whole Push() can be replaced (thanks to lvalue references (Type&), std::min and aggregate initialization) with: void push(Stack*& top, int n) { top = new Stack{n, std::min(n, top ? top->min : n), top}; std::cout << "ok\n"; } I'm new to C++ programming. I used to write in Python Good job. Sadly, such teaching shows C++ as something too old and horrifying. Edit here's a new in Push, so there should most likely be a delete in Pop That's right (thanks to @molbdnilo). You should delete popped elements instead of just leaking them.
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 100 100 100 100 160 My code simply does 2 loops and adds an space after each number (and a newline after every row). Is there an easy way to print nicely formatted matrix in cpp. Something that would be more readable like so: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 60 60 60 60 60 0 0 0 0 0 0 60 60 100 100 160 Code: for(int i = 0; i <= n ; i++){ for(int w = 0; w <= W ; w++){ std:cout<<some_array[i][w]<<" "; } std::cout << std::endl; }
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, 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, 100, 100, 100, 100, 160}}; for (int i = 0; i < 3; i++) { for (int w = 0; w < 31; w++) { s = std::to_string(K[i][w]); sz = s.size(); maxwidth = std::max(maxwidth, sz); } } maxwidth++; // we need to print 1 extra space than maxwidth for (int i = 0; i < 3; i++) { for (int w = 0; w < 31; w++) { std::cout << K[i][w]; s = std::to_string(K[i][w]); sz = (maxwidth - s.size()); while (sz--) std::cout << " "; } std::cout << std::endl; } return 0; } Output: 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 100 100 100 100 160
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) { height=hei; } }; void Box::getvolume() { double volume=0.0; volume= length*breadth*height; cout<<volume; } 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"; box1.getvolume; return 0; } in the most recent code which i've uploaded i receive error: statement cannot resolve address of overloaded function i have tried shifting get volume inside the class using double and void return type and calling the function with and without scope resolution operator and also tried calling the function as a value of another variable volume1.
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"; box1.getvolume(); return 0; } you just need to change box1.getvolume to box1.getvolume()
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 too much work to standardize/ too big of a compile slowdown, or are there other reasons? Basic example of what I would want: void fn(){ std::array<int,5> arr{1,2,3,4,5}; const auto filtered = arr | std::views::filter([](auto){return true;}); filtered.begin(); // does not compile // --would be nice if we could do // const auto filtered = arr | std::views::filter([](auto){return true;}) | eval_begin; // --now filtered.begin() can be called }
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 make a const-iterable view out of it with subrange. Obvious this requires the filter_view to be kept alive while the subrange is.
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(void *ctx, struct sk_buff* skb) { struct tcphdr* th; int dest; char msg[] = "hello world! My dest is %d\n"; th = tcp_hdr(skb); dest = th->dest; bpf_trace_printk(msg, sizeof(msg), dest); //comment this line can make program run return 0; } char _license[] SEC("license") = "GPL"; //hello_user.c #include "bpf_load.h" int main(void) { if (load_bpf_file("hello_kern.o")) return -1; read_trace_pipe(); return 0; } Compiling was just fine. But when I run this program the following error happened: bpf_load_program() err=13 0: (b7) r1 = 680997 1: (63) *(u32 *)(r10 -8) = r1 2: (18) r1 = 0x2073692074736564 4: (7b) *(u64 *)(r10 -16) = r1 5: (18) r1 = 0x20794d2021646c72 7: (7b) *(u64 *)(r10 -24) = r1 8: (18) r1 = 0x6f77206f6c6c6568 10: (7b) *(u64 *)(r10 -32) = r1 11: (69) r1 = *(u16 *)(r2 +178) R2 !read_ok processed 9 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0 I tried comment the line of "bpf_trace_printk" and program just run successfully (without anything printed out). Did I use bpf_trace_printk wrong? btw is there any well-organized ebpf tutorial or documents I can refer to? I can only find some tutorial blogs. If anyone knows please tell me. thx :)
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(struct pt_regs *ctx) { struct sk_buff *skb= (struct sk_buff *)PT_REGS_PARM1(ctx); struct tcphdr *th; unsigned short dest; char msg[] = "hello world! My dest is %u\n"; bpf_probe_read(&th, sizeof(struct tcphdr *), &(skb->data)); // bpf_probe_read(th, sizeof(struct tcphdr *), (skb->data)); Wrong! idk why. bpf_probe_read(&dest, sizeof(unsigned short), &(th->dest)); bpf_trace_printk(msg, sizeof(msg), ntohs(dest)); return 0; } char _license[] SEC("license") = "GPL";
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_; }; which requires the callable F to be copy_­constructible, this also prevents us from passing in the callable that captures the move only object into transform_view (Godbolt): #include <ranges> #include <memory> struct MoveOnlyFun { std::unique_ptr<int> x; MoveOnlyFun(int x) : x(std::make_unique<int>(x)) { } int operator()(int y) const { return *x + y; } }; int main() { auto r = std::views::iota(0, 5) | std::views::transform(MoveOnlyFun(1)); } Since the view is not required to be copy_constructible, why do we require the callable to be copy_constructible? why don't we just use moveable-box to store callable instead of copyable-box? What are the considerations behind this? Update: The recent proposal P2494R0 also addresses this issue and proposes a detailed resolution.
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). The change to make view only require movable came later. It is probably possible to relax the restriction, but it will need a paper and isn't really high priority.
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 file to the tmp file and vise-versa. The process is working for all, string, ostringstream and stringstream. I want the copying of data to happen fast and also with minimum memory consumption. An EXAMPLE with string: void write(std::string& data) { std::ifstream fileIN("smth.txt"); std::ofstream fileTMP("smth.txt.tmp"); std::string line = ""; while(getline(fileIN, line)) fileTMP << line << std::endl; fileIN.close(); fileTMP.close(); std::ifstream file_t_in("smth.txt.tmp"); // file tmp in std::ofstream fileOUT("smth.txt"); fileOUT << data; while(getline(file_t_in, line) fileOUT << line << std::endl; fileOUT.close(); file_t_in.close(); std::filesystem::remove("smth.txt.tmp"); } Should I use string for that or ostringstream or stringstream? What is the advantage of using one over the other?
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 useless and expensive inside a loop. you code copies the data twice. It is much more efficient if possible to build a temp file by copying (as your code currently does) and then remove the old file and rename the temp one with the original name. That way you only copy once the data, because renaming a file is a cheap operation.
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; } else { for (i = 2; i < low ; ++i) { if (low % i == 0) { isPrime = false; break; } } } if (isPrime){ isPrime2 = true; otrs = low+2; if (otrs == 0 || otrs == 1) { isPrime2 = false; } } else{ for (c = 2; c < otrs ; ++c) { if (otrs % c == 0) { isPrime2 = false; break; } } } if(isPrime && isPrime2) cout<<"The difference of "<<otrs<<" and "<<low<<" is 2."<<endl; ++low; For example this is the output from interval 2-20: The difference of 4 and 2 is 2. The difference of 5 and 3 is 2. The difference of 7 and 5 is 2. The difference of 9 and 7 is 2. The difference of 13 and 11 is 2. The difference of 15 and 13 is 2. The difference of 19 and 17 is 2. The difference of 21 and 19 is 2. as you can see the pairs with numbers 4 9 15 21 shouldn't be outputted because they are not prime numbers and I wanted to know whats wrong with my code so I can fix this issue
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; } int main() { unsigned int low = 2, high = 20; bool isPrime, isPrime2; while (low < high) { isPrime = is_prime(low); if (isPrime){ isPrime2 = is_prime(low + 2); } if(isPrime && isPrime2) cout<<"The difference of "<<low+2<<" and "<<low<<" is 2."<<endl; ++low; } } It's easier to understand and already outputs the correct thing: The difference of 5 and 3 is 2. The difference of 7 and 5 is 2. The difference of 13 and 11 is 2. The difference of 19 and 17 is 2. It can be further improved by removing unnecessary variables and checking all the odd numbers (because even numbers are not prime obviously). Also prime checking doesn't need to be for all numbers in range [2; n], it can be done in range [2; sqrt(n)+1] #include <iostream> #include <string> #include <cmath> using namespace std; bool is_prime(unsigned int n) { if (n <= 1) return false; for (int i = 2; i < sqrt(n)+1; ++i) { if (n % i == 0) { return false; } } return true; } int main() { unsigned int low = 2, high = 20; if (low % 2 == 0) ++low; while (low < high) { if(is_prime(low) && is_prime(low + 2)) cout<<"The difference of "<<low+2<<" and "<<low<<" is 2."<<endl; low += 2; } } The last improvement would be to not check the same number twice, e.g when low == 5 we check 5 and 7, and on the next we check 7 and 9. So we check every single number twice. How to solve this problem - I'm leaving to you
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 want via the menu below: " << endl; cout << "1.) Hero Power " << endl; cout << "2.) " << endl; cout << "3.) How does Item Power work? " << endl; cout << "4.) " << endl; cin >> choice; switch (choice) { case 1: { cout << "Enter Hero's level: "; cin >> Level; cout << "Enter Melee's power level: "; cin >> Melee; cout << "Enter secondary's Melee/Ranged power level: "; cin >> MeleeRanged; cout << "Enter Necklace's power level: "; cin >> Necklace; cout << "Enter Charm's power level: "; cin >> Charm; cout << "Enter Trinket's power level: "; cin >> Trinket; ItemTotal = Melee + MeleeRanged + Necklace + Charm + Trinket; Hero = 10 * Level + ItemTotal / 5; cout << "Your Hero Power is: " << Hero << endl; cout << "Would you like to reselect something in the menu?" << endl; cout << "(Y for Yes) (N for No)"; cin >> choice; break; At the end of Case statement 1, 2, 3, and 4 I want to be able to ask a question, have the user type Y or N, and if Y then repeat the menu before to select a new or the same choice. How can I do this?
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)"; cin >> ch; } while (ch != 'N'); This menu-driven program will continue until you enter the choice as 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 then terminate isn't even called. Digging a little bit deeper it seem to be the linux function waitpid is called. And it always returns -1 (which means some error has occured, rather than 0, which would mean: Yes the process is still running). WIFSIGNALED return 1 and WTERMSIG returns 5. Am I doing something wrong here?
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 why this constructor exists, but let's focus on the question. Detached processes cannot be joined or terminated. The terminate() call is a no-op. I would suggest writing the logic yourself - the code is not that complicated (POSIX kill or TerminateProcess). If you want you can cheat by using implementation details from the library: #include <boost/process.hpp> #include <iostream> namespace bp = boost::process; int main(int argc, char** argv) { for (std::string_view arg : std::vector(argv + 1, argv + argc)) { bp::child::child_handle pid{std::atoi(arg.data())}; std::cout << "pid " << pid.id(); std::error_code ec; bp::detail::api::terminate(pid, ec); std::cout << " killed: " << ec.message() << std::endl; } } With e.g. cat & ./sotest $! Prints
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(){ cout << "Sum of m1 & m2 is " << calc << endl; } }; int main() { trial t1; t1.setdata(3, 8); t1.getcalc(); system("pause>0"); return 0; } Output: Sum of m1 & m2 is -1717986920
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 update calc by adding calc = m1 + m2; in setdata().
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 << 10 << '\n'; std::cout << s.str(); return 0; } However, when I run this I get a runtime exception: "Access violation reading location ...". Can you please tell me, where's the mistake in my code?
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 in the tree — the task in the root. At each moment of time, p processes choose at most p ready tasks and perform them. After that, tasks whose parents were performed become ready for the next moment of time. Once the task becomes ready, it stays ready until it is performed. You shall calculate the smallest number of time moments the system needs to perform all the tasks. Input: The first line of the input contains the number of tests t (1≤t≤5⋅105). Each of the next t lines contains the description of a test. A test is described by two integers h (1≤h≤50) and p (1≤p≤104) — the height of the full binary tree and the number of processes. It is guaranteed that all the tests are different. Output: For each test output one integer on a separate line — the smallest number of time moments the system needs to perform all the tasks Example: input: 3 3 1 3 2 10 6 output: 7 4 173 I am a new C++ learner, so I thought of this way to solve this question: I count all the nodes (pow(2,height)-1) For each row I count the available nodes and put an if statement which says: If the available nodes at this row are smaller than the processors number then count++, else while the available nodes are bigger than zero (node_at_m -= m[i]) [node_at_m = Nodes available at this row; m[i] = processors number given in the question] It gives correct answer for the first 2 cases which is (3 1) and (3 2) but it gives me wrong answer on the third case (10 6), so here is my code: #include <iostream> #include <math.h> using namespace std; int main() { int t, node,nodeatm, count; cin >> t; int n[t], m[t]; for (int i = 0; i < t; i++) { cin >> n[i]; cin >> m[i]; node = pow(2,n[i])-1; count = 0; for(int q = 0; q < n[i]; q++) { nodeatm = pow(2,q); if(nodeatm <= m[i]) { count++; } else while(nodeatm > 0) { nodeatm -= m[i]; count++; } } cout << count << endl; } return 0; } I am really not a big fan of posting Codeforces questions on here, but I couldn't find any resource for this question on the Internet... Waiting your answers, thanks.
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> using namespace std; int main() { int t, node,nodeatm, count; cin >> t; int n[t], m[t]; for (int i = 0; i < t; i++) { cin >> n[i]; cin >> m[i]; node = pow(2,n[i])-1; count = 0; int rem = 0; for(int q = 0; q < n[i]; q++) { nodeatm = pow(2,q) + rem ; if(nodeatm <= m[i]) { count++; rem = 0; } else { while(nodeatm >= m[i]) { nodeatm -= m[i]; count++; } rem = nodeatm; } } if( rem ) { count++; } cout << count << endl; } return 0; } Following is a bit simplified code. You can see it working here: #include <iostream> #include <math.h> using namespace std; int main() { int t; cin >> t; for (int i = 0; i < t; i++) { int rem = 0, n, m, count = 0; cin >> n >> m; for(int q = 0; q < n; q++) { int nodeatm = pow(2,q) + rem; if( nodeatm < m) { count++; rem = 0; } else { count += ( nodeatm/ m ); rem = ( nodeatm % m ); } } if( rem ) count++; cout << count << endl; } return 0; }
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; class hexnum { private: char hex[DIM]; public: hexnum(); void print(); }; hexnum::hexnum() { /* hex[0] = '0'; hex[1] = '0'; hex[2] = '0'; hex[3] = '0'; hex[4] = '0'; hex[5] = '0'; */ for(int i = 0; i<DIM; i++) { hex[i] = '0'; } } void hexnum::print() { for(int i; i<DIM; i++) { cout<<hex[i]; } return; } int main () { hexnum n1; n1.print(); } I cannot for the life of me figure out why! Am I missing something simple or is there something I should know? I'm still very much a coding beginner and barely started to touch on classes.
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 operator works, Ive tested it alone, but programs that work on proper brainf*** interpreters don't work on mine. Can anyone find the problem here? PS: file_str::read(file); is a custom method I implemented which works. just to let you know. this is my code so far. // Read File std::string file_data; file_data = file_str::read(file); // Array int array[30000]; bool running = true; // pos int pos = 0; int pos_in_stack = 0; // Handle brackets std::vector<int> brackets; // Main Loop while(running) { if(pos > file_data.size()-1) { break; } // check what the curren command is and execute if(file_data.at(pos) == '>') { pos_in_stack++; pos++; continue; } if(file_data.at(pos) == '<') { pos_in_stack--; pos++; continue; } if(file_data.at(pos) == '+') { array[pos_in_stack]++; pos++; continue; } if(file_data.at(pos) == '-') { array[pos_in_stack]--; pos++; continue; } if(file_data.at(pos) == '.') { char a = array[pos_in_stack]; std::cout << a; pos++; continue; } if(file_data.at(pos) == ',') { std::string a; std::cin >> a; char b = a.at(0); array[pos_in_stack] = b; pos++; continue; } if(file_data.at(pos) == '[') { if(array[pos_in_stack] != 0) { brackets.push_back(pos); pos++; continue; } // find coresponding bracket else{ int brackets_looking_for = 1; while (brackets_looking_for != 0) { pos++; if(file_data.at(pos) == '[') { brackets_looking_for++; } if(file_data.at(pos) == ']') { brackets_looking_for--; } } continue; } } if(file_data.at(pos) == ']') { if(array[pos_in_stack] != 0) { pos = brackets.at(brackets.size()-1); continue; } brackets.pop_back(); pos++; continue; } } return 0; }
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 std::move_only_function<void(void)> f2{std::move(l)}; // well-formed } But unlike std::function, the standard does not define deduction guides for it (demo): #include <functional> int func(double) { return 0; } int main() { std::function f1{func}; // guide deduces function<int(double)> std::move_only_function f2{func}; // deduction failed } Is there a reason for banning CTAD?
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 means that it can't handle generic lambdas, which is a rather significant limitation on its usefulness. std::function's CTAD also comes with a disclaimer that later standards can change the deduced type (we haven't changed it yet, but we haven't removed the disclaimer either). And with move_only_function it's not just the return and argument types that are deduced. const, noexcept, and ref-qualifiers are all in play, and that introduces new design issues. For instance, does deducing from int (*)(int) deduce int(int)? Why not int(int) const - function pointers are const-callable, after all? And if CTAD turns out to be needed - and someone come up with a good design for it - it can always be added later. I don't know if these points were all raised in the LEWG discussion (the minutes are rather sparse), but I think they are more than enough to justify not supporting CTAD.
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 data. Data is and needs to be sent back and forth each frame. If I send: {"Hello"} as my first message no matter what is sent after the client only sees this To read the data on the client I am using the following code asio::read_until(socket, buffer, TRAILER); str_data=asio::buffer_cast<const char*>(buffer.data());
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 filling the contents one should .prepare()/.commit(), and after extracting content you should use .consume(). The easiest way to achieve all these with asio::streambuf is - obviously - to attach a stream: asio::streambuf buf(/*optional_max_capacity*/); /*size_t len = */asio::read_until(socket_, buf, "\n"); Now you can attach a stream std::istream is(&buf); All the usual stream operations work and wil automatically call the right buffer management functions as mentioned: std::string line; std::getline(is, line); // calls buf.consume(len) implicitly For the other types of buffers you'll have to do the "math" yourself! std::string buf; auto dynbuf = asio::dynamic_buffer(buf); size_t len = asio::read_until(socket_, dynbuf, "\n"); process_data(buf.substr(0, len)); dynbuf.consume(len); Or, worse, if you don't keep the dynamic buffer instance around, you'll have to manipulate the string itself: std::string buf; size_t len = asio::read_until(socket_, asio::dynamic_buffer(buf), "\n"); process_data(buf.substr(0, len)); buf = buf.substr(len); Needless to say, I suggest you use the simplest buffer type you need, and then use the highest abstraction (streambuf > dynamic buffer > raw container) to avoid these kinds of bugs.
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}, {"map", 5}, {"vector", 4}, {"array", 7} }; for(auto const& p : containers) std::cout << p.first << " " << p.second << '\n'; std::cout << containers.erase("map") << '\n'; // 1 std::cout << containers.erase("map") << '\n'; // 0 for(auto const& p : containers) std::cout << p.first << " " << p.second << '\n';
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 work equally well with either container, since the return value from erase(), whether it's from a map or a multimap, means exactly the same thing. P.S. Without looking it up, you should be able to make a pretty good guess what std::set's and std::multiset's erase() methods return.
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 type ColumnValue objects with 1 or more... I'd like the print function to do different things depending on what type "Value" is. Desired Result 222 "hellooooo" Code #include <iostream> template <typename Value> struct ColumnValue { std::string columnName; Value value; }; template <template<typename> typename ...X, typename ...Y> void print(std::string firstArg, const X<Y>& ...args) { for(auto val : {args...}) { std::cout << val.value << std::endl; } } int main() { ColumnValue<int> v{ .columnName="hello", .value=222 }; ColumnValue<std::string> d{ .columnName="hello", .value="hellooooo" }; print("", v, d); return 0; } Error Message : In instantiation of ‘void print(std::string, const X& ...) [with X = {ColumnValue, ColumnValue}; Y = {int, std::__cxx11::basic_string, std::allocator >}; std::string = std::__cxx11::basic_string]’: :28:19: required from here :12:5: error: unable to deduce ‘std::initializer_list&&’ from ‘{args#0, args#1}’ 12 | for(auto val : {args...}) { | ^~~ :12:5: note: deduced conflicting types for parameter ‘auto’ (‘ColumnValue’ and ‘ColumnValue >’)
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 template <typename... T> void print(std::string firstArg, const T& ...args) { (std::cout << ... << args.value) << std::endl; } If you want to insert a newline between each argument, you would need some kind of helper for that. The simplest idea would be. template <typename T> void print_helper(const T& arg) { std::cout << arg << '\n'; } template <typename... T> void print(std::string firstArg, const T& ...args) { (print_helper(args.value), ...); }
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 if I'm wrong). So, what are the rules for being able to bind const references to different types ? Is there just an additional rule like: for any type T you can bind a const reference T to it ?
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 is a base class of T2. “cv1 T1” is reference-compatible with “cv2 T2” if a prvalue of type “pointer to cv2 T2” can be converted to the type “pointer to cv1 T1” via a standard conversion sequence ([conv]). [dcl.init.ref]/5: A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows: — If the reference is an lvalue reference and the initializer expression     — is an lvalue (but is not a bit-field), and “cv1 T1” is reference-compatible with “cv2 T2”, or     [...] then the reference binds to the initializer expression lvalue [...] In your case, T1 would be const char [10] and T2 would be char [10]. T1 is reference-compatible with T2 because T2* can be converted to T1*, as it only requires adding const-qualification to the pointed type, which is a standard conversion. As you can see in the referenced sections, this is not the only case where reference binding is allowed - another case, for example, is binding a reference to a result of conversion (including user-defined). const references are also special as they are allowed to bind to rvalues. Note that this is indeed different from your previous understanding - T2 may not be convertible to T1 while you may be able to bind a reference still. Here's an example: struct A { A(int); A(A const&) = delete; }; struct B : A { B() : A(10) {} }; B b; A& ra = b; // ok, binds to base subobject A of b A a = b; // fail, A cannot be constructed from an object of B
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>; } fn id<F>(fi: F<i8>) -> F<i8> {return fi;} however this spits out a bunch of type argument not allowed errors. In C++20 I would write: template<typename<typename> M> concept monad = requires(...){...}; template<typename<typename> F> F<std::byte> id(F<std::byte> fi) {return fi;} How would I implement this functionality in Rust?
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>; fn singleton<T>(t: T) -> Self::Type<T>; fn compact<T>(mmt: Self::Type<Self::Type<T>>) -> Self::Type<T>; } struct Vector; impl Monad for Vector { type Type<T> = Vec<T>; fn singleton<T>(t: T) -> Self::Type<T> { vec![t] } fn compact<T>(mmt: Self::Type<Self::Type<T>>) -> Self::Type<T> { mmt.into_iter().flatten().collect() } } playground In a trait, Self is always a concrete type and not a type constructor. Because only concrete types satisfy traits. That's why Self<T> is not accepted. To compare and contrast with C++, in Rust you cannot refer to Vec without its type parameter as a type constructor. std::vector itself is nameable in C++. Therefore, we have to use a stand-in Vector for it in Rust. Also, our Rust implementation uses an unstable language feature. On the other hand, you'd struggle to finish writing that monad concept in C++. A template template parameter cannot be applied to any type. The type constructor is partial, and that partiality is implicit. A reasonable requirement for monad might be that it can be instantiated with any std::movable type and that the functions are defined for std::movable type parameters. That is not expressible in C++. So, in C++, you might write something like this: struct movable { movable() = delete; movable(const movable&) = delete; movable(movable&&) noexcept = default; movable& operator=(const movable&) = delete; movable& operator=(movable&&) noexcept = default; ~movable() = default; }; template<template<typename> typename M> struct type {}; template<template<typename> typename M> concept monad = requires { { singleton(type<M>{}, movable{}) } -> std::same_as<M<movable>>; // compact is similar }; In C++, you can't say a constraint holds for instantiations at all types of a certain shape (e.g. std::movable). So you create a type that is of that shape and nothing more, and require that the constraint hold at just that one instantiation. People have taken to calling these types "archetypes". You hope that there are no specializations, overloads, or other things that might stop this satisfaction from generalizing to all types of that shape. Then, you have a choice about where the functions live. Template template parameters cannot have member functions, so you either put them in a particular instantiation (e.g. M<T> is constructible from T) or as a free function. Using member functions has downsides, because it cannot be externally implemented. With a free function, you need a way to identify the monad, so you end up wrapping up the template template parameter in a stand-in type as well. These are interesting to compare.
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::vector or similar containers? How do we properly store objects in containers and keep the ability to change their values? #include <iostream> #include <functional> #include <vector> class OtherThing{ public: void addElement(std::function<int()> func){ this->myfuncs.push_back(func); } void toggle(){ std::cout << "toggle .. " << this->myfuncs[0]() << std::endl; } private: std::vector<std::function<int()>> myfuncs; }; class Thing: public OtherThing{ public: Thing(){ std::function<int()> myfunc= [this]()->int{ std::cout << "from lambda " << this->value << std::endl; return this->value; }; this->addElement(myfunc); } void setValue(int value){ this->value = value; } int getValue(){ return this->value; } private: int value; }; int main() { // container for things std::vector<Thing> mythings; // a thing Thing a; mythings.push_back(a); mythings[0].setValue(666); mythings[0].toggle(); mythings[0].setValue(999); mythings[0].toggle(); return 0; } output : clang++-7 -pthread -std=c++17 -o main main.cpp ./main toggle .. from lambda 0 0 toggle .. from lambda 0 0
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 lambda that a's constructor had stored in that vector is also copied as-is. That lambda had captured a this pointer that points at a, not the new copy. So, when you call mythings[0].setValue(), you are modifying the value of the copied Thing, but when you call mythings[0].toggle(), you are calling a lambda that prints the value of a - which was never initialized in the first place, so the output is indeterminate until a.setValue() is called. To fix this, you need to implement your own copy constructor for Thing that stores its own lambda capturing the copied Thing's this pointer, not store a copy of the earlier lambda from the Thing being copied from, eg: Thing(const Thing &src){ value = src.value; std::function<int()> myfunc = [this]()->int{ std::cout << "from copied lambda " << this->value << std::endl; return this->value; }; this->addElement(myfunc); } Online Demo
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 appreciable. compiler: g++ (Ubuntu 7.5.0-3ubuntu1~16.04) 7.5.0 related info regarding snippet smart pointer is not used intentionally it is a minimal example code. So, some portion might seem to be unnecessary. file.cpp #include <iostream> void algo_fun(unsigned int* ip_ptr_array_, unsigned int ip_size_, unsigned int** op_ptr_array_, unsigned int* op_size_) { *(op_size_) = ip_size_ + 2; // following approach is good as it allocate dynamic memory unsigned int* local = new unsigned int[*(op_size_)]; for (unsigned int i = 0; i< *(op_size_); i++) { local[i]=i+1*3; } *op_ptr_array_ = &local[0]; local[3] = 87; } int main() { // input array's contetnt unsigned int ip_size = 10; unsigned int* ip_ptr_array = new unsigned int[ip_size]; // output data unsigned int op_size; unsigned int* op_ptr_array; // filling input array for(unsigned int i = 0; i < ip_size; i++) { ip_ptr_array[i] = i+2*2; } // function calling to get output data algo_fun(ip_ptr_array, ip_size, &op_ptr_array, &op_size); delete [] ip_ptr_array; delete [] op_ptr_array; return 0; } Working version will be found here. command used to test: valgrind --leak-check=full --show-leak-kinds=all -v ./file Leak Summary from valgrind ==23138== LEAK SUMMARY: ==23138== definitely lost: 0 bytes in 0 blocks ==23138== indirectly lost: 0 bytes in 0 blocks ==23138== possibly lost: 0 bytes in 0 blocks ==23138== still reachable: 72,704 bytes in 1 blocks ==23138== suppressed: 0 bytes in 0 blocks ==23138== ==23138== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) ==23138== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
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 mallloc/free calls. Don't do that on a large application. $ valgrind --leak-check=full --trace-malloc=yes ./test --61886-- malloc(72704) = 0x5800040 --61886-- calloc(1984,1) = 0x5811C80 --61886-- calloc(104,1) = 0x5812480 --61886-- calloc(224,1) = 0x5812530 --61886-- calloc(80,1) = 0x5812650 --61886-- calloc(520,1) = 0x58126E0 --61886-- calloc(88,1) = 0x5812930 --61886-- _Znam(40) = 0x58129D0 --61886-- _Znam(48) = 0x5812A40 --61886-- _ZdaPv(0x58129D0) --61886-- _ZdaPv(0x5812A40) --61886-- free(0x5800040) ==61886== ==61886== HEAP SUMMARY: ==61886== in use at exit: 3,000 bytes in 6 blocks ==61886== total heap usage: 9 allocs, 3 frees, 75,792 bytes allocated _Znam is the mangled version of array new and _ZdaPv the mangled version of array delete from your code. The other calls to malloc/calloc/free come from libc/libstc++. You will probably see different traces on Linux or with libc++. You could use --show-reachable=yes to get information on the reachable memory. If I now run under gdb. $ gdb ./test (gdb) b malloc (gdb) b malloc (gdb) r Breakpoint 1, malloc (nbytes=96) at /usr/src/libexec/rtld-elf/rtld.c:5877 This is a call to malloc in the link loader, ld.so. I then executed several more 'r's until Breakpoint 1, __je_malloc_initialized () at jemalloc_jemalloc.c:208 Here the link loader has loaded libstdc++.so and global malloc has been replaced by jemalloc. Getting the callstack (gdb) bt #0 __je_malloc_initialized () at jemalloc_jemalloc.c:208 #1 imalloc (sopts=<optimized out>, dopts=<optimized out>) at jemalloc_jemalloc.c:1990 #2 __malloc (size=72704) at jemalloc_jemalloc.c:2042 #3 0x00000008006eb6f4 in ?? () from /usr/local/lib/gcc10/libstdc++.so.6 #4 0x000000080060e2fd in objlist_call_init (list=<optimized out>, lockstate=<optimized out>) at /usr/src/libexec/rtld-elf/rtld.c:2820 #5 0x000000080060d03d in _rtld (sp=0x7fffffffe408, exit_proc=0x7fffffffe3d0, objp=0x7fffffffe3d8) at /usr/src/libexec/rtld-elf/rtld.c:811 #6 0x000000080060a8c9 in rtld_start () at /usr/src/libexec/rtld-elf/amd64/rtld_start.S:39 #7 0x0000000000000000 in ?? () (gdb) Note the same allocation size on line #2. I'm not going to dig into what this memory is for, something part of the C++ runtime. libstdc++ (and libc) deliberately do not free this memory (presumably this is either difficult or just not worth it). In order to filter out these allocations, Valgrind uses a special function to ask libstc++/libc to free this memory. The option in this case is --run-cxx-freeres=no|yes free up libstdc++ memory at exit on Linux (strictly speaking, not just Linux). Looking at the Valgrind release notes Release 3.12.0 (20 October 2016) ... * New option --run-cxx-freeres=<yes|no> can be used to change whether __gnu_cxx::__freeres() cleanup function is called or not. Default is 'yes'. So I presume that you are using version 3.11 or earlier. Finally, if I use clang++/libc++ there is no runtime allocation (and also no freeres function).
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 of four items. I have it mostly done except one thing, the inventory array. I have it partially set up with a setInv and getInv to both set and get the inventory, but I'm uncertain on how to use getInv to put items into the inventory so I can use getInv to display it. I tried putting an already filled array in the class but the display outputs none of the items. I also tried playerOne("a"); and playerOne.setInv() = "a"; to but both fail. With the first giving me the error of "too many arguments in function call". I'm also getting the errors The second one give me two errors of "Index '4' is out of valid index range '0' to '3' for possibly stack allocated buffer 'inv'." and "Reading invalid data from 'inv': the readable size is '112' bytes, but '140' bytes may be read." I'm very new to C++ and would appreciate any help, thank you! #pragma warning(disable: 4996) #include<string> #include <iostream> #include <cstdlib> #include <string> using namespace std; //player class class player { public: //name void setName(string name) { this->name = name; } //setName end string getName() { return name; } //getName end //password void setPass(string pass) { this->pass = pass; } //setPass end string getPass() { return pass; } //getPass end //experience void setXP(int xp) { this->xp = xp; } //setXP end int getXP() { return xp; } //getXP end //position void setPosX(int xPos) { this->xPos = xPos; } //setPosX end void setPosY(int yPos) { this->yPos = yPos; } //setPosY end int getPosX() { return xPos; } //getPosX end int getPosY() { return yPos; } //getPosY end //inventory string setInv() { string inv[4]; this->inv = inv[4]; } //setInv end string getInv() { return inv; } //getInv end void display(); private: string name; string pass; string inv; int xp = 0; int xPos = 0; int yPos = 0; }; //class end void player::display() { //playerOne output cout << "Player Info - \n"; cout << "Name: " << getName() << "\n"; cout << "Password: " << getPass() << "\n"; cout << "Experience: " << getXP() << "\n"; cout << "Position: " << getPosX() << ", " << getPosY() << "\n"; cout << "Inventory: "; for (int i = 0; i < 4; i++) { getInv(); cout << "\n\n"; } //for end } int main() { //playerOne player playerOne; playerOne.setName("Porcupixel"); playerOne.setPass("PokeHerFace2008"); playerOne.setXP(1477); playerOne.setPosX(16884); playerOne.setPosY(10950); //playerTwo player playerTwo; playerTwo.setName("Commandroid"); playerTwo.setPass("RodgerRodger00110001"); playerTwo.setXP(73721); playerTwo.setPosX(6620); playerTwo.setPosY(36783); //playerThree player playerThree; playerThree.setName("BumbleBeast"); playerThree.setPass("AutoBotsRule7"); playerThree.setXP(20641); playerThree.setPosX(15128); playerThree.setPosY(46976); playerOne.display(); playerTwo.display(); playerThree.display(); return 0; } //main end
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, also from what I gather from your getInv function it looks like you're trying to store the contents of your array of strings in your private var 'inv' however you might be failing to do this since it is only a string and not an array of string, meaning it can only store ONE string or object. Answering your question more specifically, your 'getInv' is not returning anything because you are not storing anything into your string to begin with: Just to explain a little bit more. string setInv() { string inv[4]; this->inv = inv[4]; } //setInv end In this code, you are declaring a new array of strings of size 4, then saying that inv is equal to inv[4] which is never initialized therefore you're not storing anything, anyway as I explained earlier it doesn't look like the right way to do what you're trying to!
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 requires the minimum effort. A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell. For e.g., if heights = [[1,2,2],[3,8,2],[5,3,5]], the answer is 2 (in green). The code I have is: class Solution { public: vector<pair<int,int>> getNeighbors(vector<vector<int>>& h, int r, int c) { vector<pair<int,int>> n; if(r+1<h.size()) n.push_back({r+1,c}); if(c+1<h[0].size()) n.push_back({r,c+1}); if(r-1>=0) n.push_back({r-1,c}); if(c-1>=0) n.push_back({r,c-1}); return n; } int minimumEffortPath(vector<vector<int>>& heights) { int rows=heights.size(), cols=heights[0].size(); using arr=array<int, 3>; priority_queue<arr, vector<arr>, greater<arr>> pq; vector<vector<int>> dist(rows, vector<int>(cols, INT_MAX)); pq.push({0,0,0}); //r,c,weight dist[0][0]=0; //Dijkstra while(pq.size()) { auto [r,c,wt]=pq.top(); pq.pop(); if(wt>dist[r][c]) continue; vector<pair<int,int>> neighbors=getNeighbors(heights, r, c); for(auto n: neighbors) { int u=n.first, v=n.second; int curr_cost=abs(heights[u][v]-heights[r][c]); if(dist[u][v]>max(curr_cost,wt)) { dist[u][v]=max(curr_cost,wt); pq.push({u,v,dist[u][v]}); } } } return dist[rows-1][cols-1]; } }; This gets accepted, but I have two questions: a. Since we update dist[u][v] if it is greater than max(curr_cost,wt), how does it guarantee that in the end we return the minimum effort required? That is, why don't we end up returning the effort of the one in red above? b. Some solutions such as this one, short-circuit and return immediately when we reach the bottom right the first time (ie, if(r==rows-1 and c==cols-1) return wt;) - how does this work? Can't we possibly get a shorter dist when we revisit the bottom right node in future?
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 the new cell is either the same as the distance to the old cell, or it's the difference in heights, whichever is greater. Hence max(difference_in_heights, distance_to_old_cell). And Dijkstra's algorithm takes care of the minimum part of the problem statement, where instead of using a distance from the start node, we're using the "effort" needed to get from the start node to any given node. Dijkstra's attempts to minimize the distance, and hence it minimizes the effort. Dijkstra's has two closely related concepts: visited and explored. A node is visited when any incoming edge is used to arrive at the node. A node is explored when its outgoing edges are used to visit its neighbors. The key design feature of Dijkstra's is that after a node has been explored, additional visits to that node will never improve the distance to that node. That's the reason for the priority queue. The priority queue guarantees that the node being explored has the smallest distance of any unexplored nodes. In the sample grid, the red path will be explored before the green path because the red path has effort 1 until the last move, whereas the green path has effort 2. So the red path will set the distance to the bottom right cell to 3, i.e. dist[2][2] = 3. But when the green path is explored, and we arrive at the 3 at row=2, col=1, we have dist[2][2] = 3 curr_cost=2 wt=2 So dist[2][2] > max(curr_cost, wt), and dist[2][2] gets reduced to 2. The answers to the questions: a. The red path does set the bottom right cell to a distance of 3, temporarily. But the result of the red path is discarded in favor of the result from the green path. This is the natural result of Dijkstra's algorithm searching for the minimum. b. When the bottom right node is ready to be explored, i.e. it's at the head of the priority queue, then it has the best distance it will ever have, so the algorithm can stop at that point. This is also a natural result of Dijkstra's algorithm. The priority queue guarantees that after a node has been explored, no later visit to that node will reduce its distance.
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 is created from a Blueprint as well. Error: Assertion failed: GetFName() == NAME_None [File:D:/Build/++UE4/Sync/Engine/Source/Runtime/CoreUObject/Private/UObject/UObjectBase.cpp] [Line: 130] Code: APointerReferencedActor.h (Class of shared pointer object): class SMARTPOINTERSDEMO_API APointerReferencedActor : public AActor APointersManager.h (Pointer Assignment): TSharedPtr SharedPointerObjectPtr = nullptr; APointersManager.cpp: (Pointer Assignment) SharedPointerObjectPtr = TSharedPtr(Cast(GetWorld()->SpawnActor(SharedPointerClass))); (Pointer Last Reference Reset) SharedPointerObjectPtr.Reset(); Repo Link: https://github.com/Bisher-d790/UE4-SmartPointersDemo
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 the last pointer is reset. As I understood. Source: https://dawnarc.com/2018/07/ue4-tsharedptr-tweakobjectptr-and-tuniqueptr/ https://answers.unrealengine.com/questions/23497/view.html
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 even put terminal.integrated.scrollback to 0). The function curs_set(0) doesn't return ERR when it runs in either of the terminals. Is this a problem with vscode's integrated terminal? Is there a way to fix this? Code: #include <ncurses.h> int main() { initscr(); noecho(); cbreak(); if (curs_set(0) == ERR) { addstr("Not working"); } mvaddstr(1, 1, "Random sentence."); refresh(); getch(); mvaddstr(2, 1, "Random sentence number two."); getch(); endwin(); }
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; } x/=2; while(x>0) { int lastdigit=n/x; n-=lastdigit*x; x/=2; ans=ans*10+lastdigit; } return ans; } int main() { int input; long long int a; cout<<"input = "; cin>>input; a=decimal_to_binary(input); cout<<a; } For example, if I input 30 it gives me expected output i.e. 11111. The program gives correct output up to 1023 input, but after that it gives me unexpected value. For example, if I input 1200 then output is 1420175408.
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 a string. Try this: std::string decimal_to_binary(int n) { int x=1; std::string ans; while (x<=n){ x*=2; } x/=2; while(x>0) { int lastdigit=n/x; n-=lastdigit*x; x/=2; ans=ans+(char)('0'+lastdigit); } return ans; }
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 once. I did simple backtracking with dfs, here is my code: class Solution { public: bool exist(vector<vector<char>>& board, string word) { int index = 0; for(int i = 0; i < board.size(); i++) { for(int j = 0; j < board[0].size(); j++) { if(existsUtil(board, index, word, i, j)) return true; } } return false; } bool existsUtil(vector<vector<char>> board, int index, string word, int i, int j) { if(index >= word.length()) return true; if(i < 0 || i >= board.size() || j < 0 || j >= board[0].size() || board[i][j] != word[index] || board[i][j] == '0') return false; char temp = board[i][j]; board[i][j] = '0'; index += 1; bool value = existsUtil(board, index, word, i + 1, j) || existsUtil(board, index, word, i, j - 1) || existsUtil(board, index, word, i - 1, j) || existsUtil(board, index, word, i, j + 1); board[i][j] = temp; return value; } }; This code is giving TLE for larger inputs. But in the dfs function, if I pass the board parameter by referece, that is, if I pass vector<vector<char>> &board, it passes all test cases. Why is this happening?
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 Solution { boolean flag = false; public boolean exist(char[][] board, String word) { for(int i = 0;i < board.length;i++){ for(int j = 0;j < board[0].length;j++){ if(board[i][j] == word.charAt(0)){ backtrack(board,word,1,i,j); if(flag) return true; } } } return false; } void backtrack(char[][] board, String word, int p, int row, int col){ if(board[row][col] > 255) return; else if(p > word.length() - 1){ //System.out.println(asf); flag = true; return; } board[row][col] ^= 256; //up if(row > 0 && board[row-1][col] == word.charAt(p)) { backtrack(board, word, p + 1, row - 1, col); } //down if(row < board.length - 1 && board[row+1][col] == word.charAt(p)) backtrack(board,word, p+1,row+1,col); //left if(col > 0 && board[row][col-1] == word.charAt(p)) backtrack(board,word, p+1,row,col-1); //right if(col < board[0].length - 1 && board[row][col+1] == word.charAt(p)) backtrack(board,word, p+1,row,col+1); board[row][col] ^= 256; return; } }
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 the directory is found: Dependency vulkan found: YES 1.2.162 (cached) Dependency vulkan-memory-allocator found: YES 2.3.0 (cached) Dependency glfw3 found: YES 3.3.4 (cached) Dependency threads found: YES unknown (cached) Dependency zlib found: YES 1.2.11 (cached) Dependency shaderc found: YES 2019.0 (cached) Dependency freetype2 found: YES 2.10.4 (cached) Dependency stb found: YES 20200203 (cached) Dependency tinygltf found: YES 2.5.0 (cached) Dependency eigen3 found: YES 3.3.9 (cached) Found pkg-config: /usr/bin/pkg-config (0.29.2) Found CMake: /usr/bin/cmake (3.18.4) Run-time dependency cereal found: NO (tried pkgconfig and cmake) ../meson.build:106:0: ERROR: Dependency "cereal" not found, tried pkgconfig and cmake As mentioned, the file is in the same place as all others and at the same directory level. The name of the pc file is indeed cereal.pc and this is what the file looks like: prefix=/home/makogan/.conan/data/cereal/1.3.0/_/_/package/5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9 libdir=${prefix}/lib includedir=${prefix}/include Name: cereal Description: Serialization header-only library for C++11. Version: 1.3.0 Libs: -L"${libdir}" -Wl,-rpath,"${libdir}" Cflags: -I"${includedir}" The path specified in there does exist and the files found inside the repo seem to be correct.
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) { arr = new user_defined_variable[size]; size = si; if (choice) { cout << "Constructor is called! and size of array is " << size << endl; } } user_defined_variable sum_vector() { user_defined_variable sum = 0; for (int i = 0; i < size; i++) { sum += this->arr[i]; } return sum; } }; int main() { vector<float> vec_1(3); vec_1.arr[0] = 5.6; vec_1.arr[1] = 2.12; vec_1.arr[2] = 3.004; cout << vec_1.sum_vector() << endl; return 0; } But, when I'm defining functions outside the class and making a Forward Declaration of the functions then it is giving Error The code which is giving Error is as follows #include <iostream> using namespace std; template <class user_defined_variable> class vector { int size; public: user_defined_variable *arr; vector(int, bool); user_defined_variable sum_vector(); }; 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; } } user_defined_variable vector::sum_vector() { user_defined_variable sum = 0; for (int i = 0; i < size; i++) { sum += this->arr[i]; } return sum; } int main() { vector<float> vec_1(3); vec_1.arr[0] = 5.6; vec_1.arr[1] = 2.12; vec_1.arr[2] = 3.004; cout << vec_1.sum_vector() << endl; return 0; } And the Error is class_with_error.cpp:16:1: error: invalid use of template-name 'vector' without an argument list vector::vector(int si = 1, bool choice = false) ^~~~~~ class_with_error.cpp:16:1: note: class template argument deduction is only available with -std=c++17 or -std=gnu++17 class_with_error.cpp:6:7: note: 'template<class user_defined_variable> class vector' declared here class vector ^~~~~~ class_with_error.cpp:25:1: error: 'user_defined_variable' does not name a type user_defined_variable vector::sum_vector() ^~~~~~~~~~~~~~~~~~~~~ class_with_error.cpp: In function 'int main()': class_with_error.cpp:39:26: error: no matching function for call to 'vector<float>::vector(int)' vector<float> vec_1(3); ^ class_with_error.cpp:12:5: note: candidate: 'vector<user_defined_variable>::vector(int, bool) [with user_defined_variable = float]' vector(int, bool); ^~~~~~ class_with_error.cpp:12:5: note: candidate expects 2 arguments, 1 provided class_with_error.cpp:6:7: note: candidate: 'constexpr vector<float>::vector(const vector<float>&)' class vector ^~~~~~ class_with_error.cpp:6:7: note: no known conversion for argument 1 from 'int' to 'const vector<float>&' class_with_error.cpp:6:7: note: candidate: 'constexpr vector<float>::vector(vector<float>&&)' class_with_error.cpp:6:7: note: no known conversion for argument 1 from 'int' to 'vector<float>&&' Please help if you know the answer Some of the reference StackOverflow articles are Forward Declaration of Template Function forward declaration and template function error
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: template <class user_defined_variable> vector<user_define_variable>::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; } } There are other issues with your code, as you can see from the errors you're getting, but we'll focus on this one.
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 destructor is not marked explicitly noexcept. This declaration is interpreted that it is not noexcept in C++14 and it is noexcept starting in C++17. Implementations seem to strengthen this and mark in noexcept in C++14 (which is allowed): https://godbolt.org/z/WPh8zs7WE The current draft does not say much about destructor, except that it destroys target object. See [func.wrap.func.con]/31: ~function(); Effects: If *this != nullptr, destroys the target of this. Some requirements for target object are listed in constructor parameter, [func.wrap.func.con]/8 through [func.wrap.func.con]/11. Specifically, it is Lvalue-Callable and Cpp17CopyConstructible. However I don't see where it is specified that the target object destructor does not throw. Is it specified anywhere? Or is destructor of function not meant to be noexcept?
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 requirements on the implementation. In particular, the effects are undefined in the following cases: [...] If any [...] destructor operation exits via an exception, unless specifically allowed in the applicable Required behavior: paragraph.
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+b; } void fun(int a, int b, void (*ptr)(int, int)) { (*ptr)(a,b); }
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 the same automatic conversion, although the specification of this is spread across several clauses in the standard. Thus, in fun(3,4, &sum);, sum is not converted to a pointer because it is the operand of &. But then the & takes the address, producing a pointer to the function. Alternatively, in fun(3,4, sum);, sum is automatically converted to a pointer to the function, producing the same result. In (*ptr)(a,b), the * and parentheses are unnecessary. The function call operator, (…), technically takes a pointer to a function as its left operand, so ptr(a, b) supplies that pointer. In (*ptr)(a,b), *ptr dereferences the pointer, producing a function designator. Then this function designator is automatically converted back to a pointer. Thus, the expression is equivalent to (&*ptr)(a, b), which is equivalent to ptr(a, b). In fact, if you write (**ptr)(a, b), *ptr becomes &*ptr as above, and then *&*ptr produces the function designator again, and that is automatically converted again, yielding &*&*ptr, which is equivalent to ptr. You can add any number of * operators, and they will all be undone by the automatic conversions; you can write (**************ptr)(a, b). There is also an automatic adjustment of function parameter declarations corresponding to the automatic conversion. If a parameter is declared to be a function, as in the ptr of void fun(int a, int b, void ptr(int, int)), it is automatically adjusted to be a pointer to a function, as if it had been written void fun(int a, int b, void (*ptr)(int, int)).
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(this->my_char_array); i++) { std::cout << "Comparing: " << this->my_char*_array[i] << std::endl; auto value = std::find(splitted_input.begin(), splitted_input.end(), (std::string) this->my_char_array[i]); if ( value != end(splitted_input) ) { matched_keywords.push_back(this->keywords[i]); } } I am iterating over an const char*, looking for a literal that could be inside a vec<string>. When I use the std::find algorithm, the for loop stops on the first iteration (std::cout just outputs the first value on my_char*_array). Never faced an issue like that. Any idea? Thanks in advice.
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 than actually are in you array which is causing UB (undefined behaviour). The usual solution is to divide by element size: for (int i = 0; i < sizeof(this->my_char_array)/sizeof(this->my_char_array[0]); i++) { or even better, replace array with std::array, example: static constexpr std::array<const char*, 2> my_char_array = {"dsds", "dddd"}; and for (int i = 0; i < my_char_array.size(); i++) { and don't forget to #include <array>
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->next_node; node->next_node = this->next_node; } void Compact::createSeatReservation(Passenger p) { SeatNode seat(p); seat.insertAfter(this->driver_seat.getNextNode()); } If it works as intended Compact::createSeatReservation(Passenger p) should create a SeatNode object called seat and it should insert seat after a SeatNode object called driver_seat. Forming a linked list with driver_seat as the head node and seat as the next node after driver_seat. As I said I'm relatively new to c++ any help will be appreciated.
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 driver in step 1, so this assignment doesn't change anything. What you want to do in your second assignment is to change the next pointer of the driver to the newly inserted seat, which you can do this way: node->next_node = this; There's also a problem inside the createSeatReservation() method: When you call insertAfter() with the node after the driver the new seat will be inserted after the seat that itself is after the driver. Here the correct line would be: seat.insertAfter(this->driver_seat); So the complete correct code would be void SeatNode::insertAfter(SeatNode* node) { // insert this->SeatNode after node this->next_node = node->next_node; node->next_node = this; } void Compact::createSeatReservation(Passenger p) { SeatNode seat(p); seat.insertAfter(this->driver_seat); }
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 see I'm doing something wrong in the string to double switch, but i am a novice in C++ and i don't know what the problem is exactly. Here's what I tried: #include <iostream> int main() { std::string input = "82+5*8-4/"; double output, num; num = input.at(0); for (int i = 1; i < input.size() - 1; i = i + 2) { switch (input.at(i + 1)) { case '+': output = num + input.at(i); break; case '-': output = num - input.at(i); break; case '*': output = num * input.at(i); break; case '/': output = num / input.at(i); break; default: break; } num = output; } std::cout << output << std::endl; return (0); }
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 '+': output = num1 + num2; break; case '-': output = num1 - num2; break; case '*': output = num1 * num2; break; case '/': output = num1 / num2; break; default: break; } num1 = output; } std::cout << output << std::endl; return (0); }
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). What I want is to give up instantly, as soon as the unsolvable path is detected (since it is a local disk file anyway). This is an example HTML I am loading: <html> <head> <script src="//test/test.js"></script> <head> <body> <img src="image.jpg"> <img src="/image.jpg"> <img src="//image.jpg"> </body> </html> Simplified code (C++ Builder) with no error checking: WideString URL = "file:///" + StringReplace(ExtractFilePath(Application->ExeName), "\\", "/", TReplaceFlags() << rfReplaceAll) + "_test.htm"; TCppWebBrowser* WB = CppWebBrowser1; DelphiInterface<IMoniker> pMoniker; OleCheck(CreateURLMonikerEx(NULL, URL.c_bstr(), &pMoniker, URL_MK_UNIFORM)); DelphiInterface<IHTMLDocument2> diDoc2 = WB->Document; DelphiInterface<IPersistMoniker> pPrstMnkr; OleCheck(diDoc2->QueryInterface(IID_IPersistMoniker, (LPVOID*)&pPrstMnkr)); DelphiInterface<IBindCtx> pBCtx; OleCheck(CreateBindCtx(0, &pBCtx)); pPrstMnkr->Load(0, pMoniker, pBCtx, STGM_READWRITE); Problem - image.jpg loads fine, but the paths //test/test.js and /image.jpg and //image.jpg take a very long time to resolve/load. From what I understand CreateURLMonikerEx is supposed to use file:///path/to/executable/ and prepend that automatically to these paths in which case they would fail instantly - file:///path/to/executable//test/test.js for example. That does not happen. I additionally tried to move image.jpg to a subfolder and then create custom IMoniker interface with the GetDisplayName and BindToStorage implementation which loaded the image from a custom path. However it doesn't do the same for paths which start with // or /. Even though I output file:///path/to/executable/ in the GetDisplayName through the *ppszDisplayName parameter. How can I avoid extended time loading such unusable links (discard them), or redirect them to local path as above? I found a partial solution to use about:blank in the *ppszDisplayName but then it doesn't load images with the valid path image.jpg as then it loads them as about:image.jpg which again is invalid path. Additionally - I've tried adding IDocHostUIHandler interface with the implementation of Invoke method (DISPID_AMBIENT_DLCONTROL) with the pVarResult->lVal = DLCTL_NO_SCRIPTS | DLCTL_NO_JAVA | DLCTL_NO_RUNACTIVEXCTLS | DLCTL_NO_DLACTIVEXCTLS | DLCTL_NO_FRAMEDOWNLOAD | DLCTL_FORCEOFFLINE; - it it blocks the download of images entirely, but still does check 20-30 seconds for the links starting with // or /.
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 time and no guidance of any kind here, I believe that it is not possible to avoid this wait 20-30 sec when the links are invalid. I found another solution and if someone wants to supplement this solution, feel free to do so. Instead what I had to do is to create an instance of CLSID_HTMLDocument (IHTMLDocument3 or IHTMLDocument2 interface) and then load the document into that container and parse the links prior to doing anything with them. This is described on: https://learn.microsoft.com/en-us/previous-versions/aa703592(v=vs.85) This also helped: How to load html contents from stream and then how to create style sheet to display the html file in preview pane (like HTML preview handler) After parsing the document URLs and fixing the invalid ones, it can be saved/displayed in the actual TWebBrowser. Rough solution (C++ Builder): try { DelphiInterface<IHTMLDocument2> diDoc2; OleCheck(CoCreateInstance(CLSID_HTMLDocument, NULL, CLSCTX_INPROC_SERVER, IID_IHTMLDocument2, (void**)&diDoc2)); DelphiInterface<IPersistStreamInit> diPersist; OleCheck(diDoc2->QueryInterface(IID_IPersistStreamInit, (void**)&diPersist)); OleCheck(diPersist->InitNew()); DelphiInterface<IMarkupServices> diMS; OleCheck(diDoc2->QueryInterface(IID_IMarkupServices, (void**)&diMS)); DelphiInterface<IMarkupPointer> diMkStart; DelphiInterface<IMarkupPointer> diMkFinish; OleCheck(diMS->CreateMarkupPointer(&diMkStart)); OleCheck(diMS->CreateMarkupPointer(&diMkFinish)); // ...Load from file or memory stream into your WideString here... DelphiInterface<IMarkupContainer> diMC; OleCheck(diMS->ParseString(WideString(MsgHTMLSrc).c_bstr(), 0, &diMC, diMkStart, diMkFinish)); DelphiInterface<IHTMLDocument2> diDoc; OleCheck(diMC->QueryInterface(IID_PPV_ARGS(&diDoc))); DelphiInterface<IHTMLElementCollection> diCol; OleCheck(diDoc->get_all(&diCol)); long ColLen = 0; OleCheck(diCol->get_length(&ColLen)); for (int i = 0; i < ColLen; ++i) { DelphiInterface<IDispatch> diItem; diCol->item(OleVariant(i), OleVariant(i), &diItem); DelphiInterface<IHTMLElement> diElem; OleCheck(diItem->QueryInterface(IID_IHTMLElement, (void**)&diElem)); WideString wTagName; OleCheck(diElem->get_tagName(&wTagName)); if (StartsText("img", wTagName)) { OleVariant vSrc; OleCheck(diElem->getAttribute(OleVariant("src"), 4, vSrc)); // Make changes to vSrc here.... // And save it back to src OleCheck(diElem->setAttribute(OleVariant("src"), vSrc, 0)); } else if (StartsText("script", wTagName)) { // More parsing here... } } } catch (EOleSysError& e) { // Process exception as needed } catch (Exception& e) { // Process exception as needed } After full parsing of all required elements (img/src, script/src, base/href etc.) save and load into TWebBrowser. I only now have to see if the parsed HTML IHTMLDocument2 can be directly assigned to TWebBrowser without loading it again, but that is another question (See - Assigning IHTMLDocument2 instance to a TWebBrowser instance)