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
73,022,014
73,022,139
Why can MyClass foo() access private default constructor?
The following code: #include <iostream> using namespace std; class Myclass { private: Myclass (); public: int num; }; int main() { Myclass foo(); return 0; } Compiles without any warnings or errors in Eclipse. However #include <iostream> using namespace std; class Myclass { private: Myclass (); public: int num; }; int main() { Myclass foo; return 0; } Gives me this error: error: 'Myclass::Myclass()' is private within this context Why does foo give me this error while foo() doesn't? Is foo() being mistaken as a function or does date_type name() have a special meaning?
Why can MyClass foo() access private default constructor? It cannot (fancy hacks that allow you to call a private constructor aside). Is foo() being mistaken as a function Myclass foo(); is a function declaration. The mistake is to expect it to be something else. To call the constructor write: Myclass foo; // or Myclass foo{}; As this mistake is rather common, compilers typically warn about it. Don't ignore warnings, and crank up the warning level when there was no message for your code.
73,022,324
73,022,753
Heapsort with a selectable amount of children
Im trying to write some code that could sort an array using heapsort. The heap have two children right now but i want the user to be able to choose the amount of children in the heap(d in the function heapsort). Question: How do i make the function heapsort able to recieve a number (d) from the user and sort the array with heapsort with that amount of children? template <typename T> void heapify(T arr[], int n, int i) { int biggest = i; int leftChild = 2 * i + 1; int rightChild = 2 * i + 2; if (leftChild < n && arr[leftChild] > arr[biggest]) { biggest = leftChild; } if (rightChild < n && arr[rightChild] > arr[biggest]) { biggest = rightChild; } if (biggest != i) { swap(arr[i], arr[biggest]); heapify(arr, n, biggest); } } template <typename T> void heapsort(T arr[], int n, int d) { for (int i = n / 2 - 1; i >= 0; i--) { heapify(arr, n, i); } for (int i = n - 1; i > 0; i--) { swap(arr[0], arr[i]); heapify(arr, i, 0); } }
Just because you made it so easy: template <typename T> void heapify(T arr[], int n, int d, int i) { int biggest = i; int childrenStart = d * i + 1; int childrenEnd = childrenStart + d; if (childrenEnd > n) { childrenEnd = n; } for (int child = childrenStart; child < childrenEnd; ++child) { if (arr[child] > arr[biggest]) { biggest = child; } } if (biggest != i) { swap(arr[i], arr[biggest]); heapify(arr, n, d, biggest); } } template <typename T> void heapsort(T arr[], int n, int d) { if (n<=0) { return; } for (int i = (n-2) / d; i >= 0; i--) { heapify(arr, n, d, i); } for (int i = n - 1; i > 0; i--) { swap(arr[0], arr[i]); heapify(arr, i, d, 0); } }
73,022,498
73,022,869
Error while opening png image with Gdk::Pixbuf::create_from_resource
I'm trying to read the png image with Gdk::Pixbuf::create_from_resource: #include <iostream> #include <gtkmm.h> int main(int argc, char *argv[]) { auto app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base"); Gtk::Window window; window.set_default_size(100, 100); try { Glib::RefPtr<Gdk::Pixbuf> image = Gdk::Pixbuf::create_from_resource("image.png"); } catch (const Glib::Error &error) { std::cerr << "Failed to load an image: " << error.what() << std::endl; } return app->run(window); } But an error occurs: $ ./a.out Failed to load an image: The resource at “image.png” does not exist $ ls -l total 128 -rwxrwxr-x. 1 user user 36528 Jul 18 15:01 a.out -rw-r--r--. 1 user user 88792 Jul 18 15:00 image.png -rw-r--r--. 1 user user 449 Jul 18 15:00 main.cpp gtkmm version 3.24.6
If you want to load an image file directly into your program, instead of: Glib::RefPtr<Gdk::Pixbuf> image = Gdk::Pixbuf::create_from_resource("image.png"); you would use the following statement: Glib::RefPtr<Gdk::Pixbuf> image = Gdk::Pixbuf::create_from_file("image.png"); If you do want to use the image file as a resource, you would need to first generate a resource file with the "glib-compile-resources" function using a resource definition XML file. For example. glib-compile-resources --target=image.c --generate-source resource.xml In your XML file, you probably would have some type of definition such as the following. <gresources> <gresource prefix="Image"> <file preprocess="xml-stripblanks">image.png</file> </gresource> </gresources> Then in your program, your creation statement would be similar to the following. Glib::RefPtr<Gdk::Pixbuf> image = Gdk::Pixbuf::create_from_resource("Image/image.png"); Finally, you would revise your compile command to include the generated resource file with your "main.cpp" file to create your program. g++ -Wno-format -o a.out main.cpp image.c `pkg-config --cflags --libs gtkmm-3.0` `pkg-config --cflags --libs gdkmm-3.0` Hope that clarifies things. Regards.
73,022,556
73,026,329
QT C++ app crashing when send data with serial port
I am simply trying to send data via serial port, but I am getting segment fault error. When I click void productDetail::on_detailSaveBtn_clicked()) I got thıs error The inferior stopped because it received a signal from the operating system. Signal name : SIGSEGV Signal meaning : Segmentation fault Debug shows arron on this line { return write(data.constData(), data.size()); } Can someone help me please how can I solve it? Here is my code. productdetail.h #ifndef PRODUCTDETAIL_H #define PRODUCTDETAIL_H #include <QDialog> #include <QSerialPort> namespace Ui { class productDetail; } class productDetail : public QDialog { Q_OBJECT public: explicit productDetail(QWidget *parent = nullptr); ~productDetail(); private slots: void on_detailSaveBtn_clicked(); private: Ui::productDetail *ui; void connectSerial(); QSerialPort *serial1; }; #endif // PRODUCTDETAIL_H productDetail.cpp #include "productdetail.h" #include "ui_productdetail.h" #include <QDebug> #include <QSerialPort> #include <QMessageBox> productDetail::productDetail(QWidget *parent) : QDialog(parent), ui(new Ui::productDetail) { ui->setupUi(this); } productDetail::~productDetail() { delete ui; } void productDetail::connectSerial(){ //Set serial port name serial1->setPortName("COM3"); //Open serial port serial1->open(QIODevice::WriteOnly); //set baud rate serial1->setBaudRate(9600); //Set the number of data bits serial1->setDataBits(QSerialPort::Data8); //Set parity serial1->setParity(QSerialPort::NoParity); //Set stop bit serial1->setStopBits(QSerialPort::OneStop); //set flow control serial1->setFlowControl(QSerialPort::NoFlowControl); } void productDetail::on_detailSaveBtn_clicked() { serial1->write(ui->productDesp->text().toLatin1()); }
If you run your code through cgdb, lldb, or any debugger in any IDEs, it will tell you where it is crashing. Based on your further clarification, it seems that you are trying to call a method on an instance of QSerialPort which has not been constructed yet. You need to create the serial port instance as per the examples I authored in QtSerialPort. Also, if you make it a member of your class, you do not really need to construct and allocate this instance on the heap. You could just as well allocate this on the stack avoiding further complexities. In other words, just remove the star from here and then the -> pointer member references. QSerialPort serial1;
73,022,595
73,023,178
Impossible conditional statement
bool flag = ((idx == n) ? true : false); if (C[idx]->n < t) fill(idx); if (flag && idx > n) C[idx - 1]->deletion(k); The above code snippet is part of the BTree implementation, I searched everywhere but I can't find will the second if-statement will ever be executed? The flag will only be true when the idx == n, Right? and the if statement will execute only if idx > n and flag = true, which is impossible. I think that the fill(idx) is changing value but I can't understand how? Someone explain fill function void BTreeNode::fill(int idx) { if (idx != 0 && C[idx - 1]->n >= t) borrowFromPrev(idx); else if (idx != n && C[idx + 1]->n >= t) borrowFromNext(idx); else { if (idx != n) merge(idx); else merge(idx - 1); } return; }
After implementing my version, I get to know that the in some conditions the fill function is calling another function named merge that is changing the value of n. When child-node can't borrow either from left-sibling or right-sibling they will merge with the parent, Which results in a change in the value of n void fill(int pos) { ... else { if (pos != no_of_keys) merge(pos); else merge(pos - 1); } } merge function void merge(int pos) { Node *child = childs[pos]; Node *sibling = childs[pos + 1]; child->keys[no_of_keys] = keys[pos]; child->no_of_keys++; for (int i = 0; i < sibling->no_of_keys; i++) { child->keys[i + t] = sibling->keys[i]; child->no_of_keys++; } if (!child->leaf) for (int i = 0; i < sibling->no_of_keys + 1; i++) child->childs[i + t] = sibling->childs[i]; for (int i = pos; i < no_of_keys - 1; i++) keys[i] = keys[pos + 1]; for (int i = pos + 1; i < no_of_keys; i++) child[i] = child[pos + 1]; no_of_keys--; }
73,022,841
73,025,381
Different colors of COLOR_WINDOW in Windows 10 and Windows XP
In Windows 10 color of window equal of background colors of GUI elements. However, in Windows XP color of window is white, that is not equal of background colors of elements. WNDCLASSEX configuration: WNDCLASSEX wincl; //... wincl.hbrBackground = (HBRUSH)COLOR_WINDOW; // Set background color //... if (!RegisterClassEx (&wincl)) return 1; What is color I should use as window background in Windows XP?
COLOR_3DFACE/COLOR_BTNFACE is the color constant you are looking for. COLOR_WINDOW is the color inside a text box. GetSysColor function Value Meaning COLOR_3DFACE15 Face color for three-dimensional display elements and for dialog box backgrounds. COLOR_BTNFACE15 Face color for three-dimensional display elements and for dialog box backgrounds. The associated foreground color is COLOR_BTNTEXT. You must add +1 to the system color constant when using it as a class brush: WNDCLASSEXA structure WNDCLASSEXW structure hbrBackground Type: HBRUSH A handle to the class background brush. This member can be a handle to the brush to be used for painting the background, or it can be a color value. A color value must be one of the following standard system colors (the value 1 must be added to the chosen color). If a color value is given, you must convert it to one of the following HBRUSH types: Why do I have to add one when setting a class background brush to a system color? To make sure that the result is not zero. The COLOR_SCROLL­BAR system color is index zero. If we didn’t add one to the system color indices, then an attempt to set the background color to the scroll bar color would end up with (HBRUSH)0, which is a null pointer. When the system saw that you set hbrBackground to a null pointer, it wouldn’t know whether you meant the window to have no background color (null pointer), or whether you wanted it to have the system scroll bar color (COLOR_SCROLL­BAR).
73,023,102
73,023,493
Trivially copyable class - what has changed in C++20?
The standard says A trivially copyable class is a class: (1.1) that has at least one eligible copy constructor, move constructor, copy assignment operator, or move assignment operator ([special], [class.copy.ctor], [class.copy.assign]), (1.2) where each eligible copy constructor, move constructor, copy assignment operator, and move assignment operator is trivial, and (1.3) that has a trivial, non-deleted destructor ([class.dtor]). Now, I am not completely sure what it means. Does it mean that it is enough to have one of these? For example a class with trivial copy constructor and copy assignment operator and explicitly deleted move constructor and move assignment operator is trivially copyable, or it means that I have non-deleted "big 6" and every one of them is trivial? If I read this literally, having just one constructor or assignment operator should be enough. It was the case before c++20 according to cppreference. If nothing has changed (namely I still can have deleted assignment operators or constructors) why was the wording changed? What is the difference between pre c++20 and C++20 standard meaning? Update The experiments (such as the one in the answer by Spencer) show that my guess was correct. What I do not understand - why change the wording in C++20 standard. Has anything actually changed? A link to c++17 definition. In c++17 the definition was: A trivially copyable class is a class: (6.1) where each copy constructor, move constructor, copy assignment operator, and move assignment operator ([class.copy], [over.ass]) is either deleted or trivial, (6.2) that has at least one non-deleted copy constructor, move constructor, copy assignment operator, or move assignment operator, and (6.3) that has a trivial, non-deleted destructor. Are there any subtle differences between old definition and the new one?
What is the difference between pre c++20 and C++20 standard meaning? For pre-C++20 classes, none. For post-C++20 classes, the difference is constraints. The old wording talked about special member functions being "non-deleted". The new wording talks about them being "eligible." Eligible is defined in [special]/6: An eligible special member function is a special member function for which: the function is not deleted, the associated constraints ([temp.constr]), if any, are satisfied, and no special member function of the same kind is more constrained ([temp.constr.order]). You can think of it as the C++17 rule only had the first bullet while the C++20 rule adds the next two bullets (C++17 didn't have constraints so these latter two bullets are trivially satisfied). The reason for this can be found in the paper that added this wording, P0848 (Conditionally Trivial Special Member Functions) (my paper). The goal is for this to do the right thing, which is that optional<int> is trivially copyable, optional<string> is copyable but not trivially copyable, and optional<unique_ptr<int>> isn't copyable: template <class T> struct optional { // #1 optional(optional const&) requires copyable<T> && trivially_copyable<T> = default; // #2 optional(optional const&) requires copyable<T>; }; Before P0848, both #1 and #2 were considered copy constructors of optional<int>, and because #2 isn't trivial, it would fail the requirement that every copy constructor is trivial. But it doesn't matter that #2 isn't trivial, since #1 is really the only important copy constructor - and the new C++20 rules ensure that this is the case. Specifically, #2 isn't eligible because #1 is more constrained, so we only care about #1 for determining whether optional<int> is trivially copyable. That copy constructor is trivial, so we're fine. On the other hand, for optional<string>, the associated constraints on #1 aren't satisfied (string isn't trivially copyable), so the eligible copy constructor is #2, which isn't trivial.
73,023,510
73,024,065
Ignore the other string from input if certain string from array is detected
I need to create a program that print out the input value if on the first line of the input exists in an array #include <stdio.h> #include <iostream> #include <string> #include <algorithm> int main() { std::string avai_commands[] = {"PRINTAGE","CREATE"}; // Both must have the same functionality std::string insert; while(std::getline(std::cin,insert) && insert != "quit") { if(std::find(std::begin(avai_commands), std::end(avai_commands),insert) != std::end(avai_commands)) { std::cout << "New item created: " << insert << std::endl; } else { std::cout << "Invalid Command"; break; } } return 0; } So in this case on the input I wrote: CREATE main_text now that the console throws "Invalid Command" (which what I was expected to happens). But my main goal is I want to make it so that the main_text to be print if the CREATE or PRINTAGE is detected on the first line of the input. For instance, lets say I wrote this on the console: CREATE Hello then the input 'Hello' should be print.
You need to parse your input. For example, you can split every line you enter and verify if it starts with the commands you want: #include <iostream> #include <string> #include <vector> #include <algorithm> #include <sstream> int main() { std::string avai_commands[] = {"PRINTAGE","CREATE"}; // Both must have the same functionality std::string insert; while(std::getline(std::cin, insert) && insert != "quit") { if (insert == "") continue; std::string command, item; std::vector<std::string> items; std::stringstream ss(insert); if (!std::getline(ss, command, ' ')) { std::cout << "Wrong input" << '\n'; break; } while (std::getline(ss, item, ' ')) { items.push_back(item); } if (items.size() == 0) { std::cout << "Usage: PRINTAGE|CREATE <argument>" << '\n'; break; } if(std::find(std::begin(avai_commands), std::end(avai_commands), command) == std::end(avai_commands)) { std::cout << "Invalid Command" << '\n'; break; } std::cout << "New item created: "; for (auto& item : items) std::cout << item << ' '; } }
73,024,001
73,024,053
Overriding a pure virtual function with inline implementation
I've come across a piece of code which boils down to this: class Base { virtual void foo() = 0; }; class Derived : public Base { inline void foo() { /* Implementation */} }; I know the person who wrote this code is coming from a C background, so it may not be a correct practice. I understand that Derived::foo is implicitly virtual, but I'm a bit confused on whether the implementation of a pure virtual function can be inlined at all. Is this considered an ok practice? Does this inline function actually get placed in the vtable (although I imagine it would result in a compiler error otherwise)? Also, is inline keyword completely redundant, as definition in the class should imply inlining in the first place?
The method is already implicitly inline because it appears in the class definition. inline is not what you think it is. It is not to control whether calls to the function are inlined by the compiler. The compiler will decide this independent of the attribute inline. It merely says: The definition can be in a header, no problem with multiple definitions will arise. For example you could place all this in a header: class Derived : public Base { void foo(); }; inline Derived::foo() { /* implementation */ } When the member function definition is in the class body then it is implicitiy inline.
73,024,149
73,024,328
Why can't the std::string constructor take just a char?
While using a function template, I was looking at how to convert a char into a length 1 string in C++, and I saw that std::string(1, c) converted the char into a string using the fill constructor, following the logic of "repeat char c 1 time to form a string." However, there is no constructor overload defined for std::string that takes in just a char and turns it into a std::string. Why is this, and what was the design decision behind not including this constructor? It feels like a very natural and intuitive idea to be able to convert a char into a string directly rather than having to use a fill constructor. My goal is to be able to use chars and std::strings uniformly.
In C and C++, char serves double-duty. It represents both a character and a number. It is considered an integral type, which means that it participates in implicit integer promotion to many other integral types, as well as implicit conversion from other integral types. Because char is overloaded, it is impossible at the level of a function's interface to know if a user passed in an actual character (a character literal or a variable of type char) or a numeric literal that just so happens to be small enough to fit into a char. As such, when using char in an interface, one must be careful of accidental conflicts with what the user is providing. Sequence container types (types that hold a number of elements in a sequence unrelated to the values of those elements) usually have a constructor that takes a count of Ts. This is the number of elements to create in the sequence, constructed via value initialization (there is also has a version that takes a T which is used to copy-initialize these elements, which is what you used). But basic_string is special; it doesn't have such a constructor. If you tried to do std::string s(4);, you would get a compile error. However, if you make the change you want, std::string s(4); would compile and execute. But it would not give you a sequence of 4 value-initialized characters. It would give you a string containing a single character with a value of 4. This is because the integer literal 4 can be converted to a char implicitly. It's bad enough that basic_string is not consistent with the expectations of the common sequence container interface. But to actively make it compile but have radically different behavior would be way worse. Furthermore, you can use list initialization to get what you want more explicitly: std::string s1{some_char}; std::string s2 = {4}; //converts 4 to `char` std::string s3 = {other_char}; List initialization is how we initialize containers of T with a sequence of Ts.
73,024,572
73,053,969
Make a child class inherit specific attributes from two different parent classes?
I have a problem with a Diamond inheritance exercise. I have one base class A. Here is its constructor : A::A(std::string name) : _hp(10), _ep(10), _ad(0) { std::cout << "A object created !" << std::endl; return ; } Then, I have two parent classes B and C. Here are their constructors: B::B(std::string name) : A(name) { std::cout << "B object created !" << std::endl; this->_hp = 100; this->_ep = 50; this->_ad = 20; return; } C::C(std::string name) : A(name) { std::cout << "C object created !" << std::endl; this->_hp = 100; this->_ep = 100; this->_ad = 30; return ; } And finally, I have one child class . Here is its constructor: D::D(std::string name) : A(name + "_comes_from_A") { this->_name = name; std::cout << "D object created !" << std::endl; this->_hp = C::_hp; this->_ep = B::_ep; this->_ad = C::_ad; return; } The D class inherits from class B and C. The B and C classes both inherits from class A. I did something like this : class A { // code here protected: std::string _name; int _hp; int _ep; int _ad; }; class B : virtual public A { // code here }; class C : virtual public A { // code here }; class D : public B, public C { // code here }; As it can be noticed in the constructor of D class, I want it to inherits _ep from the B class (50) and _hp and _ad from the C class (100 and 30). However, if I check the value of the _ep value in my D class, (with something like this for instance) : std::cout << "ENERGY POINTS " << this->_ep << std::endl; it is always equal to 100 (which comes from the C class). I have noticed it depends on the order in which I handle inheritance for D class but I would like to be able to access values of any of the parent class from my child class. Can someone help me with that ? Thanks in advance! MINIMAL REPRODUCIBLE EXAMPLE : class A { public : A(){ return ; }; A(std::string name) : _hp(10), _ep(10), _ad(0){ std::cout << "A object created !" << std::endl; return ; }; ~A(){ std::cout << "A object " << this->_name << " destroyed." << std::endl; return ; }; protected: std::string _name; int _hp; int _ep; int _ad; }; class B : virtual public A { public : B(){ return ; }; B(std::string name) : A(name){ std::cout << "B object created !" << std::endl; this->_hp = 100; this->_ep = 50; this->_ad = 20; return ; }; ~B(){ std::cout << "B object " << this->_name << " destroyed." << std::endl; return ; }; }; class C : virtual public A { public : C(){ return ; }; C(std::string name) : A(name){ std::cout << "C object created !" << std::endl; this->_hp = 100; this->_ep = 100; this->_ad = 30; return ; }; ~C(){ std::cout << "C object " << this->_name << " destroyed." << std::endl; return ; }; }; class D : public B, public C { public : D(){ return ; }; D(std::string name) : A(name + "_comes_from_a"){ this->_name = name; std::cout << "D object created !" << std::endl; this->_hp = C::_hp; this->_ep = B::_ep; this->_ad = C::_ad; std::cout << "HIT POINTS " << this->_hp << std::endl; std::cout << "ENERGY POINTS " << this->_ep << std::endl; std::cout << "ATTACK DAMAGE " << this->_ad << std::endl; return; } ~D(){ std::cout << "D object " << this->_name << " destroyed." << std::endl; return ; }; }; int main(void) { D obj_D("TEST"); return (0); }
Okay, I got my program to work properly. Maybe I didn't explain well what I wanted to do, but I'm posting my solution here. There are 4 classes A, B, C and D. They all have _hp, _ep and _ad variables. D inherits from B AND C, which in turn inherit from A.          A        /     \       B     C        \      /           D I wanted my D class to take : _ep value from the B class _hp and _ad values from the C class Here is the minimal reproducible example of the code that worked for me : # include <iostream> # include <string> class A { public : A(){ return ; }; A(std::string name) : _hp(10), _ep(10), _ad(0){ std::cout << "A object created !" << std::endl; return ; }; ~A(){ std::cout << "A object " << this->_name << " destroyed." << std::endl; return ; }; protected: std::string _name; int _hp; int _ep; int _ad; }; class B : virtual public A { public : B(){ return ; }; B(std::string name) : A(name){ std::cout << "B object created !" << std::endl; this->_hp = 100; this->_ep = 50; this->_ad = 20; return ; }; ~B(){ std::cout << "B object " << this->_name << " destroyed." << std::endl; return ; }; static const int EP = 50; }; class C : virtual public A { public : C(){ return ; }; C(std::string name) : A(name){ std::cout << "C object created !" << std::endl; this->_hp = 100; this->_ep = 100; this->_ad = 30; return ; }; ~C(){ std::cout << "C object " << this->_name << " destroyed." << std::endl; return ; }; static const int HP = 100; static const int AD = 30; }; class D : public B, public C { public : D(){ return ; }; D(std::string name) : A(name + "_comes_from_a"){ this->_name = name; std::cout << "D object created !" << std::endl; this->_hp = C::HP; this->_ep = B::EP; this->_ad = C::AD; std::cout << "HIT POINTS " << this->_hp << std::endl; std::cout << "ENERGY POINTS " << this->_ep << std::endl; std::cout << "ATTACK DAMAGE " << this->_ad << std::endl; return; } ~D(){ std::cout << "D object " << this->_name << " destroyed." << std::endl; return ; }; }; int main(void) { D obj_D("TEST"); return (0); } The difference with the example that I posted in the question is that I declared static const int variables (HP, EP and AD) in my B and C classes. Thus, I am now able to access the values either from B or C classes in the constructor of class D. Typically, what I did earlier was wrong : // before (not working) this->_hp = C::_hp; this->_ep = B::_ep; this->_ad = C::_ad; // now (working) this->_hp = C::HP; this->_ep = B::EP; this->_ad = C::AD; The output is now : A object created ! D object created ! HIT POINTS 100 ENERGY POINTS 50 ATTACK DAMAGE 30 D object TEST destroyed. C object TEST destroyed. B object TEST destroyed. A object TEST destroyed.
73,024,981
73,025,026
C++ sort table by column while preserving row contents
Given a row-major table of type std::vector<std::vector<T>> (where T is a less-comparable type like int or std::string), I'd like to sort the table by a specific column while preserving the row contents (i.e. a row can only be moved as a whole, not the individual cells). For example, given this table: 2 8 1 4 3 7 6 7 3 3 4 9 8 6 3 4 7 1 5 7 Sorting by the 3rd column (index 2), the desired result would be: 2 8 1 4 8 6 3 4 3 3 4 9 7 1 5 7 3 7 6 7 What is the STL way of achieving this? One solution I can think of is copying the column that should be sorted into an associative container (for example std::unordered_map<T, std::size_t> where the key is the cell value and the value is the row index), then sorting the map by key (using std::sort()), extracting the resulting row index order and using that to re-order the rows in the original table. However, this solution seems non-elegant and rather verbose when writing it as actual code. What are possible, "nice" solutions to implement this? Note: The table type of std::vector<std::vector<T>> is a given and cannot be changed/modified.
Use a comparator that compare the element to compare. std::vector<std::vector<T>> vec; // add elements to vec int idx = 2; std::sort(vec.begin(), vec.end(), [idx](const std::vector<T>& a, const std::vector<T>& b) { return a.at(idx) < b.at(idx); }); Full working example: #include <iostream> #include <vector> #include <algorithm> typedef int T; int main() { std::vector<std::vector<T>> vec = { {2, 8, 1, 4}, {3, 7, 6, 7}, {3, 3, 4, 9}, {8, 6, 3, 4}, {7, 1, 5, 7} }; int idx = 2; std::sort(vec.begin(), vec.end(), [idx](const std::vector<T>& a, const std::vector<T>& b) { return a.at(idx) < b.at(idx); }); for (size_t i = 0; i < vec.size(); i++) { for (size_t j = 0; j < vec[i].size(); j++) { std::cout << vec[i][j] << (j + 1 < vec[i].size() ? ' ' : '\n'); } } return 0; }
73,025,746
73,043,511
What does python do inside the gdb debugger?
I was debugging a C++ program in the gdb debugger and tried to access the 5th element of vector which only contains 4 element. After trying this error was on the screen: (gdb) list main 1 #include <memory> 2 #include <vector> 3 4 int main(int argc, char *argv[]){ 5 6 7 std::vector<int> v_num = {1, 3, 5, 67}; 8 std::unique_ptr<std::vector<int>> p(&v_num); 9 10 (gdb) p v_num.at (5) Python Exception <class 'IndexError'> Vector index "5" should not be >= 4.: Error while executing Python code. (gdb) I didn't except to see a Python exception inside the the gdb. Can someone explain why I encountered such error? Does gdb uses python internally?
Does gdb uses python internally? Yes, it uses Python a lot to extend itself in many ways, see https://sourceware.org/gdb/onlinedocs/gdb/Python.html#Python. What you discovered is called Python Xmethods, see https://sourceware.org/gdb/onlinedocs/gdb/Xmethods-In-Python.html. Xmethods are used as a replacement of inlined or optimized out method defined in C++ source code. libstdc++ has a number of xmethods for standard containers. You can see them with info xmethod command. For std::vector there are 6 xmethods defined on my box: libstdc++::vector size empty front back at operator[] You can disable all xmethods with disable xmethod command. If you do it, GDB will unable to call at method: (gdb) p v_num.at (5) Cannot evaluate function -- may be inlined
73,025,780
73,026,534
Does calling a member variable of constexpr struct omits a whole constructor evaluation?
Let's say I have the following structure: struct MyData { int minSteps{1}; int maxSteps{64}; double volume{0.25/7}; }; constexpr MyData data() { return MyData(); } Does any of expressions below make an instance of the MyData structure constructed somewhere before the value is assigned? int steps = data().minSteps; const int maxSteps = data().maxSteps; constexpr double volume = data().volume;
It's very unlikely an instance of MyData will actually be created if you compile your code with optimizations on. Any modern compiler should optimize it out. GCC will do so even at O0, MSVC will optimize it out at O1, so it's fair to say you likely don't need to worry about it if you don't intend to compile your code with optimizations completely turned off. Take a look at it on Compiler Explorer.
73,025,998
73,248,280
How to access protected members
I have a MockAlgoController class which has protected inheritance of ControllerMockParams. How to access these protected fields outside, i.e. when asserting in tests? struct ControllerMockParams { int numCtx{0}; MockAlgo firstAlgo{Interface::first, numCtx}; MockAlgo secondAlgo{Interface::second, numCtx}; } class MockAlgoController : protected ControllerMockParams, public AlgoController { public: MockAlgoController() : AlgoController( ControllerMockParams::firstAlgo, ControllerMockParams::secondAlgo) { } MOCK_METHOD0(foo(), void()); // (...) } How do I expose the firstAlgo and secondAlgo so they are accessible outside, i.e. for assertion: EXPECT_CALL(mockAlgoController.firstAlgo, bar()) // bar() is defined in MockAlgo class.
To access protected fields outside you must not use protected in the first place. So your code should be like: class MockAlgoController : public ControllerMockParams, public AlgoController { public: MockAlgoController() : AlgoController( ControllerMockParams::firstAlgo, ControllerMockParams::secondAlgo) { } MOCK_METHOD0(foo(), void()); // (...) } When a class uses public member access specifier to derive from a base, all public members of the base class are accessible as public members of the derived class and all protected members of the base class are accessible as protected members of the derived class (private members of the base are never accessible unless friended) See documentation: https://en.cppreference.com/w/cpp/language/derived_class
73,026,053
73,026,238
#include in header and in main file (c++)
I have a project where there is a class item in a header item.h. I need to use the item class in both my main.cpp file and my player.h header. There are example files to explain my situation : main.cpp: #include "player.h" #include "item.h" #include <vector> std::vector<Item> items; int main(){ Item i; Player p; p.move(10); i.ID = 10; return 0; }; player.h: #include "item.h" #include <vector> class Player{ public: std::vector<Item> inventory; int x; void move(int i){x += i}; }; item.h: #include <string> class Item{ public: int ID; std::string name; }; It may contain errors as I didn't compiled it, and just wrote it for you to understand my situation. In my real project, I get errors for redefinition of the Item class. I'm new to C++.
You need to do this in item.h: #ifndef SOME_WORD #define SOME_WORD // the same as above //item.h content #endif You can now import item.h in all the files that you want.
73,026,741
73,026,883
how can I allow a method parameter to be null
I'm new to c++, and coming from c#; in c# to achieve my intended goal I would simply do this public void MyMethod(int? value) { if(value is null) { // Do something } else { // Do something else } } how might I achieve this result, if possible in c++?
You can do this with std::optional. void MyMethod(const std::optional<int>& option) { if(option.has_value()) { // Do something with the int option.value() } else { // Do something else with no value. } } std::nullopt is what you pass when no value is desired. MyMethod(std::nullopt); Or if you want to be able to omit the argument entirely and say MyMethod() then you can make the argument default to std::nullopt. void MyMethod(const std::optional<int>& option = std::nullopt) {
73,026,924
73,026,965
Using `static` keyword with Structured Binding
I'm trying to use C++17 structured binding to return a pair of values and I want those values to be both static and const so that they are computed the first time the function they're in is called and then they maintain their uneditable values for the lifetime of the program. However when I do this I get the error: a structured binding cannot declare an explicit storage class error and I'm not sure why or how to fix it. A minimum working example is below. #include <iostream> #include <utility> static const std::pair<double, double> pairReturn() { return {3,4}; } int main() { static const auto [a, b] = pairReturn(); std::cout << a << std::endl; std::cout << b << std::endl; return 0; }
The error is a bit confusing, but structured binding to static variables is just not supported with c++17. Either use a different solution, or c++2a. A different solution could just be an additional line: static std::pair pr = pairReturn(); auto &[a, b] = pr;
73,026,939
73,028,268
Spdlog: Only write to file if there is an error
At the moment I am combining a file sink with a console sink. (see bellow) std::vector<spdlog::sink_ptr> sinks; sinks.push_back(std::make_shared<spdlog::sinks::wincolor_stdout_sink_st>()); sinks.push_back(std::make_shared<spdlog::sinks::daily_file_sink_st>(path, 23, 59)); std::shared_ptr<class spdlog::logger> logger = std::make_shared<spdlog::logger>(name, begin(sinks), end(sinks)); I still want to log everything to the console, but only write to the file if there is an error. this is because at the moment there are a lot of useless logs and files.
You can call file_sink->set_level(spdlog::level::error) to make it log only on error and more severe levels.
73,029,184
73,032,691
Vertical order traversal of a binary tree: when nodes overlap
I am working on the LeetCode problem 987: Vertical Order Traversal of a Binary Tree: Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0). The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return the vertical order traversal of the binary tree. This is my code: class Solution { public: vector<vector<int>> verticalTraversal(TreeNode* root) { map<int, map<int, vector<int> > > nodes; // actual mapping queue<pair<TreeNode*, pair<int, int> > > q; // for storing in queue along with HD and level no. vector<vector<int>> ans; vector<int> cur_vec; if(!root){ return ans; } q.push(make_pair(root, make_pair(0, 0))); while(!q.empty()){ pair<TreeNode*, pair<int, int> > temp = q.front(); // for storing the queue.front value in temp q.pop(); TreeNode* frontNode = temp.first; int hd = temp.second.first; int level = temp.second.second; nodes[hd][level].push_back(frontNode->val); if(frontNode->left) q.push(make_pair(frontNode->left, make_pair(hd-1, level+1))); if(frontNode->right) q.push(make_pair(frontNode->right, make_pair(hd+1, level+1))); } for(auto i: nodes){ for(auto j: i.second){ for(auto k: j.second){ cur_vec.push_back(k); } } ans.push_back(cur_vec); cur_vec.resize(0); } return ans; } }; I've used a multidimensional map in my answer which maps horizontal distance to levels. It works for several test cases, but it fails to pass the test case when two nodes overlap each other and the smaller one has to come first. For instance, here the correct output for one vertical line is [1,5,6] but mine is [1,6,5] (the overlapping nodes are 6 and 5): What should I change to make it work?
In your final loop, you can just add a call to sort on the inner vector (that corresponds to a certain horizontal distance and certain level). It is in that vector you could get overlapping nodes. So: for(auto i: nodes){ for(auto j: i.second){ sort(j.second.begin(), j.second.end()); // <-- added for(auto k: j.second){ cur_vec.push_back(k); } } ans.push_back(cur_vec); cur_vec.resize(0); }
73,029,309
73,029,519
Passing shared_ptr through 2 layers of methods?
What is the most efficient way to give a shared_ptr<void> to an object that passes it to another private method before being stored in it's final destination? It's difficult to describe... maybe asking with code will illustrate the question better: class Example{ public: void give(std::shared_ptr<void> data) { // [A] which signature is best here? void give(std::shared_ptr<void> & data) { // [B] // the caller keeps it's shared_ptr m_give(data); // [A] which of these is preferable? m_give(std::move(data)); // [B] } private: void m_give(std::shared_ptr<void> data) { // [A] which signature is best here void m_give(std::shared_ptr<void> & data) { // [B] void m_give(std::shared_ptr<void> && data) { // [C] // only `give()` will ever call this m_data = data; // [A] which of these is preferable? m_data = std::move(data); // [B] } // members std::shared_ptr<void> m_data; }; How would you set up a mechanism like this?
An objective standard is needed for defining a "most efficient way". You clarified that you consider just one reference counting increment. I would suggest a slightly non-intuitive solution which does exactly this: #include <memory> class obj {}; class Example { public: void give(std::shared_ptr<obj> data) { m_give(data); } private: void m_give(std::shared_ptr<obj> & data) { m_data=std::move(data); } std::shared_ptr<obj> m_data; }; int main() { auto ptr=std::make_shared<obj>(); Example e; e.give(ptr); return 0; } If you use your debugger to run this step by step you should see that e.give(ptr); increments the reference count just once, to copy-construct give()'s parameter. The shared_ptr gets moved into its final resting place, without any further reference counting. The End. This is not the only way to achieve that, but this approach has the benefit of giving you the option of optimizing this further. If the caller wishes to give up the ownership of the shared_ptr without any reference counting taking place: e.give(std::move(ptr)); The caller effectively gives up its reference. Now, stepping through this odyssey in your debugger will show that two moves take place, one to move-construct give()'s parameter, and the same 2nd move. No change to the reference count. With some further work it might be possible to have your cake an eat it too: either have a single reference count increment to preserve the caller's ownership, and a single move operation when not. But the resulting usage syntax might be a little bit inconvenient. If the main goal is to optimize for the case where the caller preserve its ownership, as you implied, this approach results in, pretty much, a no-brainer but you will still reserve the option to decide on a case by case whether each caller can give up its ownership, and if so squeeze a little bit more juice out of this rock.
73,029,621
73,029,739
Add a source directory to a Makefile
I have the following makefile: CPP_COMPILER = g++ CPP_COMPILER_FLAGS = -g -O0 -Wall -Wextra -Wpedantic -Wconversion -std=c++17 EXECUTABLE_NAME = mainDebug CPP_COMPILER_CALL = $(CPP_COMPILER) $(CPP_COMPILER_FLAGS) INCLUDE_DIR = include SOURCE_DIR = src1 BUILD_DIR = build CPP_SOURCES = $(wildcard $(SOURCE_DIR)/*.cpp) CPP_OBJECTS = $(patsubst $(SOURCE_DIR)/%.cpp, $(BUILD_DIR)/%.o, $(CPP_SOURCES)) build: $(BUILD_DIR)/$(EXECUTABLE_NAME) TARGET_DEPS = $(CPP_OBJECTS) $(BUILD_DIR)/$(EXECUTABLE_NAME): $(TARGET_DEPS) $(CPP_COMPILER_CALL) $^ -o $@ execute: .$(BUILD_DIR)/$(EXECUTABLE_NAME) $(BUILD_DIR)/%.o: $(SOURCE_DIR)/%.cpp $(CPP_COMPILER_CALL) -I $(INCLUDE_DIR) -c $< -o $@ clean: rm -rf $(BUILD_DIR)/*.o $(BUILD_DIR)/$(EXECUTABLE_NAME) And the following folder structure: . ├── build ├── include │ ├── mylib.h │ └── test.h ├── Makefile ├── src1 │ ├── main.cc │ └── mylib.cc └── src2 └── test.cc This works correctly with src1 but when adding src2 to SOURCE_DIR, SOURCE_DIR = src1\ src2 I get the following error: /usr/bin/ld: cannot find src1: file format not recognized collect2: error: ld returned 1 exit status make: *** [Makefile:22: build/mainDebug] Error 1 What am I doing wrong here ?
Look at how you use SOURCE_DIR: SOURCE_DIR = src1 ... CPP_SOURCES = $(wildcard $(SOURCE_DIR)/*.cpp) CPP_OBJECTS = $(patsubst $(SOURCE_DIR)/%.cpp, $(BUILD_DIR)/%.o, $(CPP_SOURCES)) ... $(BUILD_DIR)/%.o: $(SOURCE_DIR)/%.cpp $(CPP_COMPILER_CALL) -I $(INCLUDE_DIR) -c $< -o $@ After you define it, you use it three times, each time as a single directory name. You cannot simply add a second name to the variable and expect Make to iterate properly over the list. First, use addsuffix to get the right pattern for wildcard: CPP_SOURCES = $(wildcard $(addsuffix /*.cpp,$(SOURCE_DIR))) Then use CPP_SOURCES instead of SOURCE_DIR: CPP_OBJECTS = $(patsubst %.cpp, $(BUILD_DIR)/%.o, $(notdir $(CPP_SOURCES))) Then use vpath to find the sources: vpath %.cpp $(SOURCE_DIR) $(BUILD_DIR)/%.o: %.cpp $(CPP_COMPILER_CALL) -I $(INCLUDE_DIR) -c $< -o $@
73,029,858
73,029,944
C++ - Does passing by reference utilize implicit conversion?
I am trying to get a better understanding of what "passing by reference" really does in c++. In the following code: #include <iostream> void func(int& refVar) { std::cout << refVar; } int main() { int val = 3; func(val); } How does func taking in a reference change the behavior of val when func is called? Is the val variable implicitly converted to a "reference" type and then passed into the function, just like how val would be converted to a float if func took in a float instead of an int? Or is it something else? Similarly, in this code: int val = 3; int& ref = val; How is a reference of val assigned to ref? Is there implicit type conversion that can be also achieved manually using a function, or does the compiler realize without converting that ref is a reference and that it needs to store the address of val?
Why don't you just try it? https://godbolt.org/z/8or3qfd5G Note that the compiler could do implicit conversion and pass a reference to the temporary. But the only (good) reason to request a reference is to either store the reference for later use or modify the value. The former would produce a dangling reference and the later would modify a value that will be deleted when the function returns and can never be accessed. So effectively this construct is just bad. The C++ gods have therefore decided that you aren't allowed to use this. Implicit conversion produces an rvalue and you can only bind a const reference to an rvalue. Binding a rvalue to a const reference is still dangerous. You should not store a const reference for later use because it can become dangling. Update: I noticed I never explained how calling a function taking a reference or assigning to a reference works. It's basically both the same thing. A reference just gives something a(nother) name. There is no type change or casting or anything involved. So when you have `func(val)` then for the duration of the function the value in val has a second name refVar. Same with int & refVal = val;. There now is a second name for the value in val called refVal. Afaik they are totally interchangeable. Note: In a function call how it works is implementation detail but most compilers pass a int * to the function under the hood.
73,030,051
73,030,093
How to query multiple lines of DNS TXT data using WinAPI
I'm trying to get DNS TXT data: #include <Windows.h> #include <WinDNS.h> #include <winsock.h> #pragma comment(lib, "Ws2_32.lib") #pragma comment(lib, "Dnsapi.lib") #include <iostream> #include <string> using namespace std; const std::string dnsAddress = "8.8.8.8"; int main() { IP4_ARRAY dnsServerIp; dnsServerIp.AddrCount = 1; dnsServerIp.AddrArray[0] = inet_addr(dnsAddress.data()); const std::wstring domain = L"mydomain.com"; DNS_RECORD* dnsRecord = nullptr; auto error = DnsQuery(domain.data(), DNS_TYPE_TEXT, DNS_QUERY_BYPASS_CACHE, &dnsServerIp, &dnsRecord, NULL); if (!error) { if (dnsRecord) { cout << "DNS TXT strings count: " << dnsRecord->Data.TXT.dwStringCount << endl; for (size_t i = 0; i < dnsRecord->Data.TXT.dwStringCount; ++i) { wcout << i << L": " << std::wstring(dnsRecord->Data.TXT.pStringArray[i]) << endl; } DnsRecordListFree(dnsRecord, DnsFreeRecordListDeep); } } } With this code I always have dnsRecord->Data.TXT.dwStringCount == 1 and it prints the first line only. I've found that WinDNS.h normally defines array for one line: typedef struct { DWORD dwStringCount; #ifdef MIDL_PASS [size_is(dwStringCount)] PWSTR pStringArray[]; #else PWSTR pStringArray[1]; #endif } DNS_TXT_DATAW, *PDNS_TXT_DATAW; What does this MIDL_PASS macro mean? When I enable it I get a lot of compile errors like identifier not found, attribute not found etc.`
DNSQuery can return multiple records, each with multiple strings. You need to enumerate the list of returned records as well as the strings within them. DNS_RECORD* pResult = dnsRecord; while (pResult != nullptr) { if (pResult->wType == DNS_TYPE_TEXT) { DNS_TXT_DATAW* pData = &pResult->Data.TXT; for (DWORD s = 0; s < pData->dwStringCount; s++) { // do something with pData->pStringArray[s] } } pResult = pResult->pNext; }
73,030,292
73,038,110
How to Run File Explorer From C++ Program and Show Only Certain Files on Windows?
I'm sorry if this question sounds a bit vague. I am making a windows 11 application in C++, and I am making an editor where I want there to be an option to upload a file of a certain type. Let's say there is a button to upload a file type; I want the file explorer to open with only the files of the chosen type to be showing. Is it possible to do this directly from my C++ program, or will I have to make own process for using the file explorer in this way?
The classic open dialog allows you to filter by file extension(s): WCHAR buffer[MAX_PATH]; OPENFILENAME ofn = {}; ofn.lStructSize = sizeof(ofn); //ofn.hwndOwner = ...; ofn.lpstrFilter = TEXT("Only text and log files\0*.TXT;*.LOG\0"); ofn.lpstrFile = buffer, ofn.nMaxFile = MAX_PATH, *buffer = '\0'; ofn.Flags = OFN_EXPLORER|OFN_ENABLESIZING|OFN_HIDEREADONLY|OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST; if (GetOpenFileName(&ofn)) DoSomethingWithFile(ofn.lpstrFile); Note: An advanced user can type * in the file name field to bypass this filter. You would think OFN_ENABLEINCLUDENOTIFY would give you more control but it does not let you filter filesystem items. MSDN is going to recommend that you use the newer Vista IFileDialog but MSDN also says about IFileDialog::SetFilter: Deprecated. SetFilter is no longer available for use as of Windows 7 (In my testing it does seem to work however (tested Windows 8 and 10)). IFileDialog supports the same basic extension filter as GetOpenFileName but unless you need to support non-filesystem items and intend to implement everything in terms of IStream, it is just extra work.
73,030,556
73,032,427
Determining size at which to switch from stack to heap allocation for multidimensional arrays
I am developing a C++ library focused on multidimensional arrays and relevant operations involving these objects. The data for my "Tensor<T,n>" class (which corresponds to an n-dimensional array whose elements are of some numeric type T) is stored in a std::vector object and the elements are accessed via indices by calculating the appropriate index in the one-dimensional data vector using the concept of strides. I understand that stack allocation is faster than heap allocation, and is generally safer. However, I also understand that heap allocation may be necessary for incredibly large data structures, and that users of this library may need to work with incredibly large data structures. My conclusion from this information is twofold: for relatively small multidimensional arrays (in terms of number of elements), I should allocate this information on the stack. for relatively large multidimensional arrays (in terms of number of elements), I should allocate this information on the heap. I argue that this conclusion implies the existence of a "breaking point" as the size of a hypothetical array increases, at which I should switch from stack allocation to heap allocation. However, I have not been successful in finding resources that might assist me in determining where exactly this "breaking point" could be implemented to optimize efficiency for my user. Assuming my conclusion is correct, how can I rigorously determine when to switch between the two types of allocation?
A std::vector has a constant size and allocates the actual data always on the heap. So no matter what matrix size you have the Matrix class will be constant size and always store data on the heap. If you want a heap-free version then you would have to implement a Matrix with std::array. You could use if constexpr to choose between vector and array. Note that heap allocation cost some time. But they also allow move semantic. The "break even" point might be as little as 4x4 matrixes but you have to test that. new/delete isn't that expensive if it can reuse memory and doesn't have to ask the kernel for more. Oh, and there is also the option of using a custom allocator for the vector.
73,030,830
73,059,267
shark failing to compile: static assert failed _DISABLE_EXTENDED_ALIGNED_STORAGE
I followed the installation guide with Visual Studio 2022 as described here. I am able to clone from git and then use cmake to produce a VS2022 sln file. However, when I attempt to build that solution in VS2022, I get the following error: Severity Code Description Project File Line Suppression State Error C2338 static_assert failed: 'You've instantiated std::aligned_storage<Len, Align> with an extended alignment (in other words, Align > alignof(max_align_t)). Before VS 2017 15.8, the member "type" would non-conformingly have an alignment of only alignof(max_align_t). VS 2017 15.8 was fixed to handle this correctly, but the fix inherently changes layout and breaks binary compatibility (only for uses of aligned_storage with extended alignments). Please define either (1) _ENABLE_EXTENDED_ALIGNED_STORAGE to acknowledge that you understand this message and that you actually want a type with an extended alignment, or (2) _DISABLE_EXTENDED_ALIGNED_STORAGE to silence this message and get the old non-conforming behavior.' shark C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.32.31326\include\type_traits 987 I am seeing this error 209 times which is also the number of projects in the cmake generated sln. When I double click on one of those errors, I am taken to a file called type_traits where I see the following code: #ifndef _DISABLE_EXTENDED_ALIGNED_STORAGE static_assert(_Always_false<_Aligned>, "You've instantiated std::aligned_storage<Len, Align> with an extended alignment (in other " "words, Align > alignof(max_align_t)). Before VS 2017 15.8, the member \"type\" would " "non-conformingly have an alignment of only alignof(max_align_t). VS 2017 15.8 was fixed to " "handle this correctly, but the fix inherently changes layout and breaks binary compatibility " "(*only* for uses of aligned_storage with extended alignments). " "Please define either " "(1) _ENABLE_EXTENDED_ALIGNED_STORAGE to acknowledge that you understand this message and " "that you actually want a type with an extended alignment, or " "(2) _DISABLE_EXTENDED_ALIGNED_STORAGE to silence this message and get the old non-conforming " "behavior."); #endif // !_DISABLE_EXTENDED_ALIGNED_STORAGE Seems like I may need to define _DISABLE_EXTENDED_ALIGNED_STORAGE. Please say what is the right way to do that?
Seems like Shark has left it to the person compiling the it to choose weather to define _ENABLE_EXTENDED_ALIGNED_STORAGE or _DISABLE_EXTENDED_ALIGNED_STORAGE. I chose the latter.
73,030,968
73,031,761
Can C++20 concept be used to avoid hiding template function from base class?
I want to use template specialization to query component of a derive object. The code below works fine. However, I am new to C++. I am not sure if such compiler behavior is reliable, and want some confirmation. #include <type_traits> class B{ public: template<class T> T* get() requires std::is_same_v< T, B>{ //... [X] return this; } }; class C : virtual public B{ public: using B::get; public: template<class T> T* get() requires std::is_same_v< T, C>{ //... [Y] return this; } }; int main(){ C c; B* b1=c.get<B>(); C* c1=c.get<C>(); B* b2=c.get<B>(); } From cppreference , even I use using B::get, If the derived class already has a member (Y) with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member (X) that is introduced from the base class. I tried to digest the quote. Please confirm these 3 statements. [X]&[Y] has the same name AND parameter list. But qualification of [X] and [Y] are difference. Thus, no hides or overrides occur. Are they all correct? If so, I will rely on this awesome behavior.
This is specified in namespace.udecl#14, emphasis mine, When a using-declarator brings declarations from a base class into a derived class, member functions and member function templates in the derived class override and/or hide member functions and member function templates with the same name, parameter-type-list ([dcl.fct]), trailing requires-clause (if any), cv-qualification, and ref-qualifier (if any), in a base class (rather than conflicting). Such hidden or overridden declarations are excluded from the set of declarations introduced by the using-declarator. As to your questions, [X]&[Y] has the same name AND parameter list. But qualification of [X] and [Y] are difference. Thus, no hides or overrides occur. Yes, [X] and [Y] are exactally the same except for the trailing requires clause. So, no hides occur.
73,031,061
73,031,296
How to get more kernel memory
I'm making a custom operating system, and I'm running into some memory issues. Recently I've had issues such as this: I've attributed characters not appearing on screen to there not being enough kernel memory, as this runs from kernel. I'm very new to asm, c++, and OS development as a whole so there could be a lot of things I've done to cause this issue. One reason I believe this is a memory-related issue is because when I shortened my kernel.cpp file, suddenly characters appeared (though if I add too many, some disappear). Here is a link to my GitHub repository with my code: https://github.com/Subwaey/KaiOS
Your boot loader only loads 2 sectors (1024 bytes) of the kernel into memory. You could increase this a little (temporarily) by changing the mov dh, 2 to a larger value at line 15 of boot.asm. This has limits (e.g. limited to 255 sectors, and possibly limited by the number of sectors per track on the disk). To break that limit you have to break it up into multiple reads (e.g. if there's 18 sectors per track, then loading a 123 KiB kernel as 7 reads of not more than 18 sectors per read). The next limit is caused by real mode only being able to access 640 KiB of RAM (where some of that is BIOS data, etc). For this reason (and because most kernels grow to be much larger than 640 KiB) you want a loop that loads the next piece of the kernel's file into a buffer, then switches to protected mode and copies that piece elsewhere (e.g. starting at 0x0100000 where there's likely to be a lot more contiguous RAM you can use), then switches back to real mode; until the whole kernel is loaded and copied elsewhere. Of course hard-coding the "number of sectors in kernel's file" directly into the boot loader is fragile. A better approach would be to have some kind of header at/near the start of the kernel's file that contains the size of the kernel; where boot loader loads the header and uses it to determine how many sectors it needs to load. Also; I suspect you don't actually have a separate file for the kernel - it's just a single file containing "boot loader + kernel". This is likely to be a major problem when you try to get the kernel to boot in different scenarios (from partitioned hard disks where boot loader has to care about which partition it was installed in, from CD-ROM where it's all completely different, from network where it's all completely different, etc).
73,031,354
73,031,587
Why c++ static member was not initialized in this case?
registerT is not called and the function was not registered in the map. I have no clue. This is the code. //factory.h #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <cstdlib> #include <cxxabi.h> template <typename BaseType, typename... Args> class Factory { public: static std::shared_ptr<BaseType> Make(const std::string &name) { return constructMap().at(name)(); } public: template <typename T> class Registrar : public BaseType { public: friend T; static bool registerT() { const auto name = "Derive"; // add constuct function to funcMap // ... return true; } static bool registered; }; private: // declare funcMap }; //base.h #include "factory.h" class Base : public Factory<Base> { public: Base() {} }; //derive.h #include <string> #include "base.h" class Derive : public Base::Registrar<Derive> { public: Derive(); }; //derive.cpp #include "derive.h" Derive::Derive() {} //main.cpp #include "base.h" int main() { std::string name = "Derive"; auto b = Base::Make(name); return 0; } Use g++ -o mian ./main.cpp -Lderive.o to get exe file. But the function registerT was not called when exec ./mian It works when using g++ -o mian ./main.cpp derive.o to get exe file. Thank you.@user17732522 The problem is solved. Thank you.
First of all, the compilation command is wrong. The -L option expects a path to a directory containing libraries which are specified later. I am not sure what you are attempting by using it here, but as a result you are not linking the derive translation unit. .o files should simply be listed like source files, e.g. g++ -o mian main.cpp derive.o (This part doesn't apply anymore after the question was edited in response.) After fixing that. The program has undefined behavior. This is because there is no guarantee that Derive::name is initialized before Factory<Base>::Registrar<Derive>::registered. In particular the latter is a specialization of a template and therefore has so-called unordered dynamic initialization, meaning that there is no ordering guarantee for it with any other global static storage duration object. However, the initialization of the latter calls registerT() which accesses the former in const auto name = T::name;. If name has not been initialized at this point, accessing it causes undefined behavior. The usual workaround is to not rely on inter-dependent dynamically-initialized static members, but instead use static functions with local static variables as you are already doing for constructMap. E.g. here you could use the same for name. Additionally, even if there was no ordering issue with the static storage duration objects you defined yourself, there is still the issue that the standard streams need to be initialized before std::cout may be used. They are initialized through construction of an object of type std::ios_base::Init. Including <iostream> behaves as if it defined a global static storage duration object of that type, which usually guarantees it is initialized before you use it. But again, here registered is unordered with it. So you must create an object of type std::ios_base::Init yourself in registerT before trying to write to std::cout.
73,032,461
73,032,707
Connect C++ signal to QML slot
I'm trying to connect a C++ signal with a QML slot. The C++ signal is called userRegistered() and the QML slot is called userRegisteredQML(). In the C++ file, I have the following: QQuickView view(QUrl::fromLocalFile("interface.qml")); QObject *topLevel = view.rootContext(); connect(myClass, SIGNAL(userRegistered()), topLevel, SLOT(userRegisteredQML())); And in the interface.qml, I have the slot userRegisteredQML: function userRegisteredQML(){ console.log("this is a test!"); } The problem is that it does not show "this a test!". Therefore, I wanted to ask you if this is the proper way to connect a C++ signal to a QML slot.
Expose your object to QML in C++: topLevel->setContextProperty("myClass", myClass); In QML, you can use Connections: Connections { target: myClass userRegistered: { // do something with it here } }
73,032,796
73,194,849
How can I wait for all data to be written before the serial port connection is terminated
I need to send data from my QT application via serial port. I am trying to send data in this way. void productDetail::on_detailSaveBtn_clicked() { if (!serial.isOpen()) { if (serial.begin(QString("COM3"), 9600, 8, 0, 1, 0, false)) { serial.send(ui->productDesp->text().toLatin1()); serial.end(); } } } As I understand it, serial connection closes without writing all data. I think closing the serial port after waiting for all the data to be written can solve my problem. How can I verify that all data is written before the serial port close? QT 5.15.2 Windows
Try to wait a few time so a portion of data can be written. Check if any left with while loop and repeat the process. serial.send(ui->productDesp->text().toLatin1()); while(serial.bytesToWrite()){ serial.waitForBytesWritten(20); } serial.end();
73,033,106
73,033,265
gcc linker: undefined reference to a symbol while target lib only contains a superclass method
I'm having repeatedly a linker error in Qt-Project containing a local Installation of Qt 5.14.2 and OpenCV 4.3 and a gcc 11 (fedora 35, x64) and in the last step bringing everything together there might be something off or not fit together: This is the last call out of the make system together with the error: g++ -Wl,-rpath,/home/qt/Qt/5.14.2/gcc_64/lib -o QtOpenCVCompatibleTest main.o mainwindow.o moc_mainwindow.o -L/home/qt/Qt/5.14.2/gcc_64/lib -lopencv_core -lopencv_videoio -lopencv_highgui /home/qt/Qt/5.14.2/gcc_64/lib/libQt5Widgets.so /home/qt/Qt/5.14.2/gcc_64/lib/libQt5Gui.so /home/qt/Qt/5.14.2/gcc_64/lib/libQt5Core.so -lGL -lpthread /usr/bin/ld: /usr/lib/gcc/x86_64-redhat-linux/11/../../../../lib64/libopencv_highgui.so: undefined reference to `QPushButton::hitButton(QPoint const&) const@Qt_5' So in short: CV needs a symbol that Qt can't deliver. The relevant parts of the .pro file: QT += core gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets INCLUDEPATH += /usr/include/opencv4/ LIBS += -L/home/qt/Qt/5.14.2/gcc_64/lib -lopencv_core -lopencv_videoio -lopencv_highgui A closer look towards the libs: nm -gDC /usr/lib64/libopencv_highgui.so | grep QPushButton U QPushButton::paintEvent(QPaintEvent*)@Qt_5 U QPushButton::qt_metacall(QMetaObject::Call, int, void**)@Qt_5 U QPushButton::qt_metacast(char const*)@Qt_5 U QPushButton::focusInEvent(QFocusEvent*)@Qt_5 U QPushButton::focusOutEvent(QFocusEvent*)@Qt_5 U QPushButton::keyPressEvent(QKeyEvent*)@Qt_5 U QPushButton::staticMetaObject@Qt_5 U QPushButton::event(QEvent*)@Qt_5 U QPushButton::setFlat(bool)@Qt_5 U QPushButton::QPushButton(QWidget*)@Qt_5 U QPushButton::QPushButton(QWidget*)@Qt_5 U QPushButton::~QPushButton()@Qt_5 U QPushButton::minimumSizeHint() const@Qt_5 U QPushButton::sizeHint() const@Qt_5 U QPushButton::hitButton(QPoint const&) const@Qt_5 U typeinfo for QPushButton@Qt_5 So yes, we need QPushButton::hitButton(QPoint const&) of Qt in opencv's highgui but the Qt Version only has: nm -gDC /home/qt/Qt/5.14.2/gcc_64/lib/libQt5Widgets.so | grep hitButton 0000000000331a00 T QToolButton::hitButton(QPoint const&) const@@Qt_5 00000000002e4990 T QRadioButton::hitButton(QPoint const&) const@@Qt_5 000000000024e060 T QAbstractButton::hitButton(QPoint const&) const@@Qt_5 000000000025d840 T QCheckBox::hitButton(QPoint const&) const@@Qt_5 ... the method of its superclass, which in fact should be enough to have something to bind to. So there are 3 Questions left: How does the early binding in c++ works along the linker - I would guess every inherited class have at least a symbol pointing towards a proper method. I've might build OpenCV with a different version of Qt (but all Qt5 Versions have QPushButton::hitButton) What is the correct calling order in gcc's linker command - I assume all Qt libs will be always called last as long as every other component depends on them? Basically: How do I get rid of that error. The local Qt Installation (on a Fedora 35 x64) is located as its own user but with all files at least accessible. A pure Qt Project just builds fine on the system.
The QPushButton::hitButton override exists in the latest Qt 5 (which is 5.15 at the time of writing), but did not yet exist in Qt 5.14. It looks like your OpenCV build was compiled with a newer set of Qt headers than the version you're linking with. Presumably these came from your system, since Fedora 35 ships with Qt 5.15.2. The only right solution is to use the correct headers for the libraries that you are linking with; anything else will just lead to more headaches. When building OpenCV, make sure you're using your local Qt distribution and not your system's version. I think (but did not test this) that you can do this by setting Qt5_DIR to /home/qt/Qt/5.14.2 in CMake.
73,033,362
73,033,548
Using multiple structs in a function c++
So i want to make a quiz program with structs. I have the question, options and the answer in a struct. But i have multiple questions(structs) so i wrote a function to nicely format the input and output. But seems like it doesn't work because i can't use variable struct in functions. Here's the code: #include <iostream> #include <string> using namespace std; struct q0{ string question = "Which sea animal has a horn?"; string arr[3] = {"Dolphin", "Clownfish", "Narwhal"}; int correctAnswer = 3; }; struct q1{ string question = "What is the biggest animal in the world?"; string arr[3] = {"Blue Whale", "Elephant", "Great White Shark"}; int correctAnswer = 1; }; void quiz(struct q){ cout<<q.question<<endl; for(int i = 0; i<3; i++){ cout<<i+1<<". "<<q.arr[i]<<endl; } int answer; cin>>answer; (answer == q.correctAnswer) ? cout<<"Correct\n"<<endl : cout<<"Inorrect\n"<<endl; } int main(){ quiz(q0); quiz(q1); }
You don't need to create a separate class-type for each question when you can create a single Question class with appropriate data members and then pass instances of that Question class to the function quiz as shown below: //class representing a single question struct Question{ std::string question; std::string arr[3]; int correctAnswer; }; void quiz(const Question& q){ std::cout<<q.question<<std::endl; for(int i = 0; i<3; i++){ std::cout<<i+1<<". "<<q.arr[i]<<std::endl; } int answer; std::cin>>answer; (answer == q.correctAnswer) ? std::cout<<"Correct\n"<<std::endl : std::cout<<"Inorrect\n"<<std::endl; } int main(){ //create object 1 of type Question Question obj1{"What is the biggest animal in the world?", {"Dolphin", "Clownfish", "Narwhal"}, 3}; //pass obj1 to function quiz(obj1); //create object 2 of type Question Question obj2{"What is the biggest animal in the world?", {"Blue Whale", "Elephant", "Great White Shark"}, 1}; //pass obj2 to function quiz(obj2); } Working Demo
73,033,460
73,034,060
Is it possible to generate multiple custom vertices using the Bundle Properties from Boost Graph Library?
I'm trying to generate an application that solves the bipartite assignment problem via the auction algorithm with the boost graph library. I found it possible to characterize vertices and edges with multiple properties using the boundle properties. But since the auction algorithm envolve two types of entities, persons and items, I was wondering if there was the possibility of generating more than one characterization of vertices in order to suppor this distinction. Thanks for the help.
This question is overly broad, but let me try to provide some helpful pointers. But since the auction algorithm [i]nvolve two types of entities, persons and items, I was wondering if there was the possibility of generating more than one characterization of vertices in order to suppor[t] this distinction. It think "But" can be dropped. Answering the question, it seems obvious that you can include a type discriminator, like: struct VertexProperties { int multiple; std::string characterizing, properties; // for auction algorithm: bool isPersonEntity; // or e.g. enum {Person, Item} entityType; }; Here's several answers that show such classifications in action using BGL: using a manual type discriminator like just mentioned: Boost graph Library using Bundled properties using variant Graph with two types of nodes showing how to use filtered_graph to "view" only part of the vertices at a time: boost::adjancency_list with polymorphic vertices and edges parsing Cars/Planes from XML Storing a nested XML structure in form of BGL graph using BOOST library using shared pointers (allowing polymorphic property types) Using boost graph library with a custom class for vertices alternatives using dynamic property maps How to use boost::graph dijkstra's algorithm if vertex properties are pointers?
73,033,734
73,505,351
Show QWidget as focused
I've got four QLineEdit placed inside of a QLineEdits, where I want the first the parent to look as if it is in focus when any of the containing ones is selected. Note: I don't want the focus to actually change, just the "focus frame" (the thin blue border) to appear on the parent LineEdit. I've tried to draw a rect, but while it works on Windows I'm running into issues of the drawn rectangle not looking like a proper rectangle on ex. Linux, where it is supposed to be rounded. Is there a way to fix this OR, if possible, just make it draw itself as focused despite focus not being on it? Here's my attempt at drawing a custom rect, but haven't been able to make it successfully mirror the OS style properly. if (childHasFocus) { QPainter painter(this); QLineEdit textBox; QColor color = textBox.palette().color(QPalette::Highlight); painter.setPen(color); QRect rect; rect.setTopLeft(QPoint(0,0)); rect.setWidth(this->width() - 1); rect.setHeight(this->height() - 1); painter.drawRect(rect); } EDIT: Added an image of the desired look. Note that I'm trying to get it to look like other LineEdits focusframe independent of OS, so hardcoding a blue rectangle won't work due to ex. Linux having a rounded focusframe. Desired look:
Here's how to do it. Its a very basic class that draws the focus frame if any of the childs have focus. On focus change, we do an update (which can probably be optimized a bit to avoid unnecessary repaints). Screenshot: class IPEdit : public QWidget { public: IPEdit(QWidget *parent = nullptr) : QWidget(parent) { delete layout(); auto l = new QHBoxLayout(this); setFocusProxy(&a); setAttribute(Qt::WA_Hover); for (auto *w : {&a, &b, &c, &d}) { l->addWidget(w); w->installEventFilter(this); } } bool eventFilter(QObject *o, QEvent *e) override { if (e->type() == QEvent::FocusIn || e->type() == QEvent::FocusOut) { update(); } return QWidget::eventFilter(o, e); } void paintEvent(QPaintEvent *e) override { QStyleOptionFrame opt; opt.initFrom(this); opt.frameShape = QFrame::StyledPanel; opt.state |= QStyle::State_Sunken; // clear mouseOver and focus state // update from relevant widgets opt.state &= ~(QStyle::State_HasFocus | QStyle::State_MouseOver); const auto widgets = {&a, &b, &c, &d}; for (const QWidget *w : widgets) { if (w->hasFocus()) { opt.state |= QStyle::State_HasFocus; } } opt.rect = contentsRect(); QPainter paint(this); paint.setClipRegion(e->region()); paint.setRenderHints(QPainter::Antialiasing); style()->drawControl(QStyle::CE_ShapedFrame, &opt, &paint, this); } private: QLineEdit a; QLineEdit b; QLineEdit c; QLineEdit d; };
73,034,238
73,034,562
Check if class is derived from templated class
I'm trying to check if a class that I'm templating is inheriting from another templated class, but I can't find the correct way to do it. Right now I have the following: #include <iostream> template <typename MemberType, typename InterfaceType> class Combination : public InterfaceType { public: Combination(); virtual ~Combination(); private: MemberType* pointer; }; class MyInterface {}; class MyMember {}; class MyCombination : public Combination<MyMember, MyInterface> { }; int main() { static_assert(std::is_base_of_v<Combination<MyMember, MyInterface>, MyCombination>); std::cout << "hello"; } Which is working fine, but in the place this template is placed, I don't have access to the template parameters definitions, and this should be quite generic. What I'd like is to test for the MyCombination class to inherit from a generic Combination without taking into account the template arguments, something like this: static_assert(std::is_base_of_v<Combination, MyCombination>); or static_assert(std::is_base_of_v<Combination<whatever, whatever>, MyCombination>); Would you know how to check for this? In this case I can't use boost libraries or other external libraries. Thanks! EDIT: I don't have access to modify the Combination class, and what I can change is the assert and the My* classes.
This can easily be done with the C++20 concepts. Note that it requires a derived class to have exactly one public instantiated base class. template <typename, typename InterfaceType> class Combination : public InterfaceType {}; class MyInterface {}; class MyMember {}; class MyCombination : public Combination<MyMember, MyInterface> {}; template<class Derived, template<class...> class Base> concept derived_from_template = requires (Derived& d) { []<typename... Ts>(Base<Ts...>&) {}(d); }; static_assert(derived_from_template<MyCombination, Combination>); Demo The equivalent C++17 alternative would be #include <type_traits> template<template<class...> class Base, typename... Ts> void test(Base<Ts...>&); template<template<class...> class, class, class = void> constexpr bool is_template_base_of = false; template<template<class...> class Base, class Derived> constexpr bool is_template_base_of<Base, Derived, std::void_t<decltype(test<Base>(std::declval<Derived&>()))>> = true; static_assert(is_template_base_of<Combination, MyCombination>);
73,034,411
73,034,644
Why a reference declaration influences my pointer?
Case 1 #include <iostream> using namespace std; int main() { int n = 1; // int & r = n; int * p; cout << &n << endl; cout << p << endl; return 0; } Output 1 0x7fffffffdc94 0 Case 2 #include <iostream> using namespace std; int main() { int n = 1; int & r = n; int * p; cout << &n << endl; cout << p << endl; return 0; } Output 2 0x7fffffffdc8c 0x7fffffffdd90 In Output 2, the pointer p just pointed to the address followed int n. Shouldn't an unintialized pointer point to some random places? Why adding a reference declaration influences the address of p pointed to?
Shouldn't an unintialized pointer point to some random places? No, an uninitialized pointer points nowhere. It has an indeterminate value. Trying to read and/or print this indeterminate pointer value as you are doing in cout << p << endl; has undefined behavior. That means there is no guarantee whatsoever what will happen, whether there will be output or not or whatever the output will be. Therefore, there is no guarantee that changing any other part of the code doesn't influence the output you will get. And there is also no guarantee that the output will be consistent in any way, even between runs of the same compiled program or multiple compilations of the same code. Practically, the most likely behavior is that the compiler will emit instructions that will simply print the value of whatever memory was reserved on the stack for the pointer. If there wasn't anything there before, it will likely result in a zero value. If there was something there before it will give you that unrelated value. None of this is guaranteed however. The compiler can also just substitute the read of the pointer value with whatever suits it or e.g. recognize that reading the value has undefined behavior and that it may therefore remove the output statement since it can not be ever reached in a valid program.
73,034,418
73,035,627
How can I print descending numbers on left side and ascending numbers on the bottom side of a box?
I have written codes to print a box with # outline but I am trying to print out a box which looks something exactly like that instead: # # # # # # # # # # # 8# # 7# # 6# # 5# # 4# # 3# # 2# # 1# # 0# # # # # # # # # # # # # 0 1 2 3 4 5 6 7 8 The codes I currently have and the output attached image: int i = Xend; int j = Yend; int side = Yend; // Yend is = 8; for (i = 0; i < Xend; i++) // Xend is = 8; { for (j = 0; j < side; j++) // Ystart is 0; { if (i == 0 || i == side - 1 || j == 0 || j == side - 1) { cout << "#" << " "; } else { cout << " "; } } cout << "\n"; } current code output
I am very sorry. But I have to do this . . . There are that many potential solutions and here is one of them: #include <iostream> #include <string_view> constexpr std::string_view box(R"( # # # # # # # # # # # 8# # 7# # 6# # 5# # 4# # 3# # 2# # 1# # 0# # # # # # # # # # # # # 0 1 2 3 4 5 6 7 8 )"); int main() { std::cout << box; } You can also do programatically: #include <iomanip> #include <string> int main() { // Print upper box row for (int i = 0; i < 11; ++i) std::cout << " #"; std::cout << '\n'; // Now print out 9 rows with number and left and right box delimiter for (int i = 0; i < 9; ++i) { std::cout << (8 - i) << '#'; for (int k = 0; k < 9; ++k) std::cout << " "; std::cout << " #\n"; } // Print lower box row for (int i = 0; i < 11; ++i) std::cout << " #"; std::cout << '\n'; // Print row with numbers std::cout << " "; for (int i = 0; i < 9; ++i) std::cout << i << ' '; std::cout << '\n'; }
73,034,442
73,034,528
how to work with deleted object on custom vector
I know that std vectors can work with objects that are not default constructible. However, when I try to implement a slightly modified one myself, I cant seem to make such vector. class A { public: A() = delete; A(const int &x) :x(x) {} private: int x; }; template <typename T, int N> //default constructor of the vector CircularBuffer<T,N>::CircularBuffer() { Size = 0; Capacity =N; Array = new T[Capacity]; Start = 0; End = 0; } template <typename T, int N> CircularBuffer<T,N>::CircularBuffer(const CircularBuffer& rhs) //copy constructor of the vector { Size = rhs.Size; Capacity = rhs.Capacity; Array = new T[Capacity]; Start = rhs.Start; End = rhs.End; for(int i=0;i<Capacity;i++) { this->Array[i] = rhs.Array[i]; } } template <typename T, int N> //move constructor of the vector CircularBuffer<T,N>::CircularBuffer(CircularBuffer&& rhs) { rhs.Swap(*this); } template <typename T, int N> void CircularBuffer<T,N>:: Swap(CircularBuffer &source) { swap(Size,source.Size); swap(Capacity,source.Capacity); swap(Start,source.Start); swap(End,source.End); swap(Array,source.Array); } When I try to make a vector with object A, CircularBuffer<A,3> v; error: use of deleted function ‘A::A()’ I get this error which is obviously self explanatory. Anyone can help me solve this??
The problem is here Array = new T[Capacity]; which default constructs T objects. std::vector uses placement new to construct objects when they are added to the vector. Array = (T*)operator new(sizeof(T)*Capacity); and (when you add the new item) new(Array + i) T(...); // placement new where ... are the arguments you wish to pass to the constructor. See here for more details.
73,034,718
73,034,955
Difference between using "struct S" or "S" as typename
In the C language the name of a structured type S ist struct S. In C++ one can also use struct S as typename instead of S as usual for struct S {}; struct S s1; // also ok in C++ S s2; // normal way in C++ So, the assumption is, that using struct S or S as typename in C++ is a matter of taste ;-) But in the following example there are places where struct S is not allowed: struct S1 { S1(int x = 0) : x{x} {} int x{}; }; typedef S1 S2; template<typename T> auto foo(T a) { // T::_; // T is deduced to `S` in all cases return S1{a}; // return struct S1{a}; // NOK } int main() { // foo(struct S1{i}); // NOK S1 s1; foo(s1); struct S1 s2{2}; foo(s2); foo(1); // struct S2 s20; // NOK S2 s21; } Can anyone explain to me what this unsymmetry is about? It looks like struct S is not allowed where a ctor call as part of an expression is needed. But if a type S could also be written as struct S it should also be ok to use struct S{} as a ctor call.
the assumption is, that using struct S or S as typename in C++ is a matter of taste ;-) The above assumption is wrong as there are exceptions to it(as also noted in your example) and the reason has more to do with C compatibility than a matter of taste. The point is that there are rules for when we can/cannot use struct S1 as a replacement for just S1. And assuming that we can always use struct S1 as a replacement for S1 is wrong. The operand of the return statement should be an expression but struct S1{a} is not an expression and hence cannot be used in the return statement: //-----vvvvvvvvvvvv----> operand is not an expression return struct S1{a}; An expression involving struct S1 would look something like: return (struct S1)a; There are also situation(s) when we need to use struct S1 and using just S1 won't work. A contrived example is given below: struct S1 { }; int S1() { std::cout<<"function called"<<std::endl; return 5; } int main() { //S1 s; // ERROR: This won't work unless we use struct S1 struct S1 s2; //WORKS }
73,035,273
73,047,493
C++ Ignore string argument
I have built a program that create,insert a text into .txt file and now I need to add a small feature where I need to write a function that displays list of files in the directory. int main() { display_duration_start(); std::string VALID_COMMANDS[] = {"CREATE_FILE;","APPEND_TEXT;","DISPLAY_FILE;"}; int sum = 0; int count = 1; std::string insert; while(std::getline(std::cin, insert) && insert != "quit") { if (insert == "") continue; std::string command, item,item1,item2; std::vector<std::string> items; std::stringstream ss(insert); if (!std::getline(ss, command, ' ')) { std::cout << "Unknown command: `" + command + "`" << '\n'; break; } while (std::getline(ss, item, ' ')) { items.push_back(item); } if (items.size() == 0) { std::cout << "Usage: " + command + " <argument>" << '\n'; continue; } if(std::find(std::begin(VALID_COMMANDS), std::end(VALID_COMMANDS), command) == std::end(VALID_COMMANDS)) { std::cout << "Command not found: " + command << '\n'; break; } for(auto& item: items) if(command == "CREATE_FILE;") { create_file(item); } if(command == "APPEND_TEXT";) { append_text(item); } if(command == "DISPLAY_FILE;") { display_file(); } } } Now that when I typed in DISPLAY_FILE; on my console then it throws this: Usage: DISPLAY_FILE; <argument>. Well obviously the output raised because it needed an argument, but how do I make it so that it doesn't need to have a argument? Function of display_file() (not sure if its necessary to be informed): void display_file() { struct dirent *d; DIR *dr; dr = opendir("C:\\schema_location"); if(dr != NULL) { printf(""); for(d=readdir(dr); d!=NULL; d=readdir(dr)) { printf("%s\n", d->d_name); } closedir(dr); } else printf("\nERROR: Cannot retrieve file from the current directory"); }
You can define a list of commands which don't need arguments and check it together with the presence of arguments. The code below should make the work int main() { //display_duration_start(); std::string VALID_COMMANDS[] = { "CREATE_FILE;","APPEND_TEXT;","DISPLAY_FILE;" }; std::string NO_ARGUMENT_COMMANDS[] = { "DISPLAY_FILE;" }; int sum = 0; int count = 1; std::string insert; while (std::getline(std::cin, insert) && insert != "quit") { if (insert == "") continue; std::string command, item, item1, item2; std::vector<std::string> items; std::stringstream ss(insert); if (!std::getline(ss, command, ' ')) { std::cout << "Unknown command: `" + command + "`" << '\n'; break; } while (std::getline(ss, item, ' ')) { items.push_back(item); } if (items.size() == 0 && std::find(std::begin(NO_ARGUMENT_COMMANDS), std::end(NO_ARGUMENT_COMMANDS), command) == std::end(NO_ARGUMENT_COMMANDS) ) { std::cout << "Usage: " + command + " <argument>" << '\n'; continue; } if (std::find(std::begin(VALID_COMMANDS), std::end(VALID_COMMANDS), command) == std::end(VALID_COMMANDS)) { std::cout << "Command not found: " + command << '\n'; break; } for (auto& item : items) { if (command == "CREATE_FILE;") { create_file(item); } if (command == "APPEND_TEXT";) { append_text(item); } } if (command == "DISPLAY_FILE;") { display_file(); } } } void display_file() { struct dirent* d; DIR* dr; dr = opendir("C:\\schema_location"); if (dr != NULL) { printf(""); for (d = readdir(dr); d != NULL; d = readdir(dr)) { printf("%s\n", d->d_name); } closedir(dr); } else printf("\nERROR: Cannot retrieve file from the current directory"); }
73,035,275
73,246,993
undefined reference to `xlCreateBookW'
While using the libxl library in QT(c++) I got this error undefined reference to `xlCreateBookW' I have tried the setup in their website, https://www.libxl.com/setup.html I added : INCLUDEPATH = C:\libxl-4.0.4.0\include_cpp LIBS += C:\libxl-4.0.4.0\lib\libxl.lib to my project.pro and the file bin/libxl.dll to the project directory. It didn't work instead the error show up, how can I solve it please? the code is in here https://www.libxl.com/home.html , i don't know i couldn't add it
i solved the problem actually the customer support guy i emailed him, he told me to choose the bin which has the same version of my compiler (mine is 64bit) so you have to choose the bin and the lib also the same version and the path: for my case (Qt_6_2_3_MinGW_64_bit compiler ) INCLUDEPATH = C:/libxl-4.0.4.0/include_cpp LIBS += C:/libxl-4.0.4.0/lib64/libxl.lib in the .pro file also you have to copy the libxl.dll from C:\libxl-4.0.4.0\bin64 (for my case) and thank you.
73,035,549
73,041,874
QT C++ Ask to user before close window
I have 2 pages, a homepage, a settings page. I open the settings page on mainwindow. when the user wants to close the settings page. I want to ask the user if you are sure you want to log out. How can I ask such a question to just close the settings page without the app closing? Mainwindow is my homepage
This is what I do in my preference dialog: PreferencesDialog::PreferencesDialog(QWidget *parent) : QDialog(parent, Qt::Tool) { ... QDialogButtonBox* buttonBox = new QDialogButtonBox(this); buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::RestoreDefaults); buttonBox->setFocusPolicy(Qt::TabFocus); mainLayout->addWidget(buttonBox); setLayout(mainLayout); connect(buttonBox, &QDialogButtonBox::rejected, this, &PreferencesDialog::reject); connect(buttonBox, &QDialogButtonBox::accepted, this, &PreferencesDialog::accept); connect(buttonBox->button(QDialogButtonBox::RestoreDefaults), &QPushButton::clicked, this, &PreferencesDialog::revert); ... } You can then do something like this in the accept slot, although I think it is a bad idea. This would result in distractive user experience. The common behaviour that an average user expects is just the above. So, I would ignore the below code. But I will provide it for you for completeness: QMessageBox messageBox; messageBox.setWindowTitle("Close the preferences?"); messageBox.setIcon(QMessageBox::Warning); messageBox.setText(...); messageBox.setInformativeText(tr("Are you sure you want to close the preferences?")); messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); messageBox.setDefaultButton(QMessageBox::No); const int ret = messageBox.exec(); switch (ret) { case QMessageBox::Yes: ... case QMessageBox::No: ... break; default: break; }
73,035,602
73,065,655
How do you wait for `QtConcurrent::run` to finish without thread blocking?
Hey this should be a pretty straightforward question. Simply put: Want to run a function in another thread. Need to wait for the function to finish. Do not want to freeze the thread though while waiting. In other words, I'd like to use an eventloop. Here is the freezing example: extern void sneed() { QEventLoop wait; wait.exec(); } int main( int argc, char *argv[] ) { QApplication a(argc, argv); { // this starts a tui QConsoleToolkit::s_CursesController.start( QCD::CursesEngine::Engine_Thread_Stdout_Monitor ); } ct_Start( "Sneed" ); QFuture<void> ff = QtConcurrent::run(sneed); ff.waitForFinished(); // This freezes the tui ct_Finish( "Chuck" ); } I tried to use a QEventLoop in the main thread instead of ff.waitForFinished(), but I could not figure out how I could emit a signal when ff was finished, because QFuture isnt a QObject, and has no finished signal that I could bind to: https://doc.qt.io/qt-6/qfuture.html I tried passing a QObject via reference to emit a signal from it instead, but couldnt get it to compile. What am I missing here?
The solution comes from a simple class called QFutureWatcher: doc.qt.io/qt-5/qfuturewatcher.html Here is some sample code for running lambda's in a different thread, and receiving its value. template <class T> auto asynchronous( auto &&lambda ) { QEventLoop wait; QFutureWatcher<T> fw; fw.setFuture( QtConcurrent::run(lambda) ); QObject::connect ( &fw, &QFutureWatcher<T>::finished, &wait, &QEventLoop::quit ); wait.exec(); QObject::disconnect( &fw, &QFutureWatcher<T>::finished, &wait, &QEventLoop::quit ); return fw.result(); } using the function would look like this: int n(0); ct_Start(n); // 0 - Running in main thread n = asynchronous<int>([&n](){ // Running in background thread. // Mainthread is waiting for this lambda to finish // but mainthread is not locked. // User Interface will still function. for ( int i = 0; i < 100000; i++ ){ ct_Debug(n++); }; return n; }); ct_Finish(n); // 100000 Note: ct_Debug ct_Start ct_Finish are not found in the Qt framework. They are debugging macros for a TUI.
73,036,208
73,036,251
Is there any difference between empty derived class and using?
I'm writing a library whose functionalities are provided in a C-compatible header like the following: // File: bar.h typedef struct bar_context_t bar_context_t; #ifdef __cplusplus extern "C" { #endif bar_context_t* bar_create(); void bar_destroy(bar_context_t*); int bar_do_stuff(bar_context_t*); #ifdef __cplusplus } #endif and implemented in C++: // File: bar.cpp namespace bar { class Context { private: // ... public: int do_stuff(); }; } The problem is how to connect bar::Context to bar_context_t so I can implement the extern C functions. I can think of two options: Option A: Using using bar_context_t = bar::Context; Option B: Empty Derived Class struct bar_context_t : public bar::Context {}; Which option is better? Or is there a better third option?
Neither is necessary (and I don't even think your first variant works; using is just C++ syntax sugar, and does not introduce a type). You just declare bar_context_t to be a pointer to bar::Context; that's it. In C, you declare it to be a void*, since C has no type safety anyways.¹ ¹strictly speaking, C has type safety, between the two types "function pointer" and "not a function pointer".
73,036,283
73,036,323
Sometimes the using namespace std; is inside main or other functions?
Usually when someone declares using namespace std; (I know that it is a bad habit), They should declare it like that: # include <iostream> using namespace std; int main() { // Some code here... return 0; } But it is a completely different story here. The using namespace std; is sometimes located in int main() (Code 1.12), Maybe in a function named Hello (Code 1.13): Code 1.12 # include <iostream> int main() { using namespace std; // Some code after namespace... return 0; } Code 1.13 # include <iostream> void Hello() { using namespace std; // Some code again... } int main() // Adding up main just to ensure there are no errors { return 0; } Why do they need to initialize using namespace std;, in a function or in function main?
The using for namespaces statement pulls in all symbols from the namespace into the current scope. If you do it in the global namespace scope then all symbols from the std namespace would be available in the global (::) namespace. But only for the current translation unit. If you do using inside the function, or even a nested block inside a function, then the symbols from std would only be pulled into that (more narrow) scope. Lets take your last example, and add some stuff to it: #include <iostream> void Hello() { using namespace std; cout << "Hello\n"; // Valid, cout is in the current scope } int main() { cout << "World\n"; // Not valid, there's no cout symbol in the current scope } Here cout is available only inside the Hello function, because that's where you added std::cout to the functions scope. In the main function there's no such symbol cout.
73,036,402
73,036,628
Efficient way to XOR two unsigned char arrays?
I am implementing an encryption algorithm and was wondering if there was a more efficient way than O(n) for xoring two unsigned char arrays? I essentially want to know if it's possible to avoid doing something like this: unsigned char a1[64]; unsigned char a2[64]; unsigned char result[64]; for (int i=0;i<64;i++) { result[i] = a1[i] ^ a2[i]; } Like I said, I know there's nothing inherently wrong with doing this but I was wondering if there was possibly a more efficient method. I need to keep my algorithm as streamlined as possible. Thanks in advance for any information!
As the comments note, the only way of doing this faster than O(n) is not doing it for all elements, In fact, don't do it for any elements! The reason is that you're writing a cryptographic algorithm. You'll use results[i] a few lines lower. That part will likely be numerically expensive, while this XOR is limited by memory bandwidth. If you replace results[i] with a1[i] ^ a2[i] in the cryptographic operation, the CPU is likely to overlap the memory access and the computation.
73,036,566
73,037,361
Understanding syntax of function parameter: vector<vector<int>> A[]
I'm solving a question where a function is defined as following: vector <int> func(int a, vector<vector<int>> B[]){ // Some stuff } I'm confused about why the second parameter is not simply vector<vector<int>> B. Why the extra [] part in the parameter? Can someone clarify the meaning of this? The vector, B, is populated by a similar code snippet: vector<vector<int>> B[10]; while(num--){ cin>>u>>v>>w; vector<int> t1,t2; t1.push_back(v); t1.push_back(w); B[u].push_back(t1); t2.push_back(u); t2.push_back(w); B[v].push_back(t2); }
Just as int foo(char str[]) is a function that takes a (c-style) array of characters, so int foo(vector<vector<int>> B[]) takes an array of vectors of vectors ... of integers. This means that it's three-dimensional data, requiring 3 indices to access the elements (fundamental data type; in this case, int), like B[i][j][k] = 5. Without the extra [] in the API it'd be two-dimensional data: a vector of vectors. Note that int foo(char str[]) is equivalent to int foo(char str[5]) which is equivalent to int foo(char * str). In C we usually add the [] to a function declaration to imply that we expect to receive an array of those elements; while * is often used when we expect at most one element. Likewise, adding the number [5] is basically just a comment to the user of the code that they expect 5 elements, but the compiler won't enforce this. These conventions carry over to C++ when we use these c-style arrays ... which is rare. With c-style arrays there's either going to be a maximum array size in the comments somewhere; or, more commonly, it's provided as an input. That may be what the first argument of the function is supposed to represent. I agree with KungPhoo here that this API looks suspiciously bad. I'd expect bugs/bad performance just because the choices seem very amateurish. The c-style array means the function can't know where the end of the c-style array is - but the vectors mean that we give up some of the (niche) benefits of c-style simplicity (especially because they're nested!). It seems to be getting the worst of both worlds. But, perhaps, there may be a very niche justification for the API.
73,037,605
73,621,458
A missing header from a repository which is linked to a shared library that is linked to my project, using cmake
I have a GitHub repository containing two cmake projects. Lets say the name of the repo is "Audio" and it contains a directory "AudioGui" and a directory "AudioLib". The "AudioLib" project is a shared library which includes and links a header from another GitHub repository. AudioLib can be built and its cmake contains: include(FetchContent) FetchContent_Declare( AudioFile GIT_REPOSITORY https://github.com/adamstark/AudioFile.git GIT_TAG 1.1.0 ) FetchContent_MakeAvailable(AudioFile) target_link_libraries(AudioLib PUBLIC Qt${QT_VERSION_MAJOR}::Core AudioFile ) AudioGui, which cannot be built but cmake returns no errors, contains in its cmake: include(FetchContent) FetchContent_Declare( Audio GIT_REPOSITORY https://github.com/myname/Audio.git GIT_TAG 1.0.1 ) FetchContent_MakeAvailable(Audio) target_link_libraries(AudioGui PUBLIC Qt${QT_VERSION_MAJOR}::Widgets Audio ) The problem is that the includes of the headers inside AudioGui can be done this way: #include "_deps/audio-src/AudioLib/Converter_global.h" #include "_deps/audio-src/AudioLib/converter.h" instead of #include "AudioLib/Converter_global.h" #include "AudioLib/converter.h" and even in that way I get an error that the header AudioFile.h (which is included in AudioLib and directly to AudioGui) cannot be found. Any ideas on what I am doing wrong?
Since AudioFile is a third party library for the client programs, AudioFile.h must not be included in AudioLib's headers (a pointer and a forward declaration of AudioFile should be used instead in order to not having external dependencies). You can see the full CmakeLists files here: https://michae9.wordpress.com/2022/09/01/shared-lib-to-be-used-by-client-programs-with-cmake/
73,038,129
73,038,421
Change value of randomly generated number upon second compilation
I applied the random number generator to my code although the first number generated doesn't change when I run the code second or the third time. The other numbers change however and the issue is only on the first value. I'm using code blocks; Cygwin GCC compiler (c++ 17). Seeding using time. #include <iostream> #include <random> #include <ctime> int main() { std::default_random_engine randomGenerator(time(0)); std::uniform_int_distribution randomNumber(1, 20); int a, b, c; a = randomNumber(randomGenerator); b = randomNumber(randomGenerator); c = randomNumber(randomGenerator); std::cout<<a<<std::endl; std::cout<<b<<std::endl; std::cout<<c<<std::endl; return 0; } In such a case when I run the code the first time it may produce a result like a = 4, b = 5, c = 9. The second and further time (a) remains 4 but (b) and (c) keep changing.
Per my comment, the std::mt19937 is the main PRNG you should consider. It's the best one provided in <random>. You should also seed it better. Here I use std::random_device. Some people will moan about how std::random_device falls back to a deterministic seed when a source of true random data can't be found, but that's pretty rare outside of low-level embedded stuff. #include <iostream> #include <random> int main() { std::mt19937 randomGenerator(std::random_device{}()); std::uniform_int_distribution randomNumber(1, 20); for (int i = 0; i < 3; ++i) { std::cout << randomNumber(randomGenerator) << ' '; } std::cout << '\n'; return 0; } Output: ~/tmp ❯ ./a.out 8 2 16 ~/tmp ❯ ./a.out 7 12 14 ~/tmp ❯ ./a.out 8 12 4 ~/tmp ❯ ./a.out 18 8 7 Here we see four runs that are pretty distinct. Because your range is small, you'll see patterns pop up every now and again. There are other areas of improvement, notably providing a more robust seed to the PRNG, but for a toy program, this suffices.
73,038,464
73,039,069
Most efficient memory order to increment an integer
I have N threads, which operates 1 variable of std::atomic type. Like this: std::atomic<int> Num = 0; void thr_func() { Num.fetch_add(1); } Here, the default memory order is memory_order_seq_cst, which is not most efficient. Which memory order and why i should use to get the most effective code and also have a consistent state of Num? I googled it, and found a lot of answers, that memory_order_relaxed but i don't understand, why something like this will not happen with it? Because documentation of relaxed order says: there are no synchronization or ordering constraints imposed on other reads or writes thr1: load Num thr2: load Num thr1: add 1 thr2: add 1 thr1: store Num thr2: store Num
std::atomics are not only about consistent state of themselves, but also about consistent state in the surrounding code. Say for example, that you use an atomic integer to store the number of items in an array. You will probably end up writing something like the following: std::atomic<int> len; ... array[len] = some_new_object; len++; In another thread you would wait for len to change and access the newly added object afterwards. For this to function properly it is crucial that the len++; statement happens strictly after the statement before. Usually the compiler as well as the processor are allowed to reorder instructions, as long as the resulting effect is the same (according to the as-if rule). For interthread synchronization you want to restrict this reordering and that is exactly what the std::atomic types do. With memory_order_seq_cst for example, the expression len++ being a read-modify-write access, will not allow any other instruction to be reordered with it. If you used memory_order_relaxed, which does not restrict instruction reordering, the len variable could end up being increased before the array[len] = some_new_object; expression is completed. That is obviously not what you want in the example above. So to conclude, in the example that you provided in your question, you might as well use memory_order_relaxed (the atomicity of the operation is still guaranteed and the output you depicted will not happen). But as soon as you use the std::atomic variable to actually signal some state between the threads, you should use memory_order_seq_cst (which is the default one for good reason).
73,038,670
73,038,811
Why are there duplicate C/C++ compilers (e.g g++, gcc)?
According to this answer, gcc and g++ have some functional differences. As confirmed by this script, the commands point to the exact same binary, effectively making them duplicates. Why is that so? $ uname Darwin $ md5 `which cc c++ gcc g++ clang clang++` fac4668657765c8dfe89d8995acfb5a2 /usr/bin/cc fac4668657765c8dfe89d8995acfb5a2 /usr/bin/c++ fac4668657765c8dfe89d8995acfb5a2 /usr/bin/gcc fac4668657765c8dfe89d8995acfb5a2 /usr/bin/g++ fac4668657765c8dfe89d8995acfb5a2 /usr/bin/clang fac4668657765c8dfe89d8995acfb5a2 /usr/bin/clang++
The executable can determine the name it was called with by inspecting the first (or zeroth) command line argument passed to it. By convention it is the name of the executable and is passed by whatever program is invoking the compiler (typically e.g. a shell). Although it is the same executable, it can then take different actions based on whether or not that value is gcc or g++. Also, the files you are seeing are unlikely to be duplicate files. They are most likely just (soft or hard) links to the same file. For the part that clang/clang++ and gcc/g++ seem to be the same, although they are completely different compilers, that is an Apple quirk. They link gcc and g++ to clang and clang++ for some reason, but in reality both refer to Apple clang, which is also different from upstream clang. It often causes confusion (at least for me).
73,038,673
73,042,882
What will the order of slot execution if two signals are emitted at the same time in same thread?
I am trying to understand the code of HMI (QT based application). Typically in a embedded software, multiple ECUs send data at the same time to the UI. In which order 2 different slots (2 different UI classes) connected to 2 different signals, be executed if both the signals are triggered at same time within the same thread? Are they being executed in parallel ? (I guess not possible since there is only 1 thread in picture)
UI classes should be typically handled in your main thread and only heavy computation that can block the UI in worker threads. So, by default, you would get them executed subsequently, and cannot certainly be in parallel in an ideal design. Yes, you are right, there is no parallelism with a single thread. Even with multiple threads involved, you would only ever see true parallelism if the receivers are in different threads. For further information on various connection types, please refer to the official Qt documentation.
73,039,528
73,039,594
c++ array[] vs malloc(). are these 2 vriables the same?
Here we have arr1 and arr2... int arr1[3]{}; int *arr2 = (int *)std::malloc(size_t(int) * 3); and i think entities of arr2 should be stored in the heap compared to the arr1 that is stored in the stack memory. question: Is there any reason to use arr2 if its not going to get bigger or smaller during the code?
The memory held by arr1 is guaranteed to be allocated only in it's scope. The memory arr2 points to is yours till you free() it (or exit the program), thus you might pass it as a return value, store it, etc. Also, arr2's allocation likely takes more bytes in practice, as memory allocation usually maintains blocks of free memory. So allocating via malloc or new is both slower and takes more memory (but sometimes required for other benefits).
73,039,817
73,040,635
How to wrap a shared pointer of a template class function in Pybind11
I want to wrap a shared pointer of a template class function in Pybind11. My class is a template queue : MyQueue.hpp template<typename Data> class MyQueue { public: std::queue <Data> the_queue; static std::shared_ptr<MyQueue<Data>> make_data_q_ptr(); }; MyQueue.cpp template<typename Data> std::shared_ptr<MyQueue<Data>> MyQueue<Data>::make_data_q_ptr(){ std::shared_ptr<MyQueue<Data>> data_q_ptr; data_q_ptr = std::make_shared<MyQueue<Data>>(); return data_q_ptr; } The type of data in MyQueue : DataType.cpp class DataType { public: uint mynumber; }; The wrapper using Pybind11 : wrap.cpp namespace py = pybind11; PYBIND11_MODULE(mymodule, m){ py::class_<MyQueue<DataType>, std::shared_ptr<MyQueue<DataType>>>(m, "MyQueue_DataType") .def(py::init<>()) .def_static("make_data_q_ptr",&MyQueue<DataType>::make_data_q_ptr); py::class_<DataType>(m, "DataType") .def(py::init<>()) .def_readwrite("mynumber",&DataType::mynumber); } Command to compile the code g++ -shared -fPIC `pkg-config --cflags --libs opencv` -lpthread -std=c++11 -I./pybind11/include/ `python3.7 -m pybind11 --includes` *.cpp -o mymodule.so `python3.7-config --ldflags` The code gets compiled successfully, but when I try to import the module that I created "mymodule", I get this error: ImportError: undefined symbol: xxx >>> import mymodule Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: /home/pi/templedpybind11/mymodule.so: undefined symbol: _ZN7MyQueueI8DataTypeE15make_data_q_ptrEv Can you please help me out? Thank you.
Move template<typename Data> std::shared_ptr<MyQueue<Data>> MyQueue<Data>::make_data_q_ptr(){ std::shared_ptr<MyQueue<Data>> data_q_ptr; data_q_ptr = std::make_shared<MyQueue<Data>>(); return data_q_ptr; } into your header file. It isn't visible at the point that needs to see it.
73,040,489
73,040,507
Why not use the root of the trie?
I'm trying to understand this program, why do they have to make Trie* pCrawl = root, why don't they just use the root of the tree and insert directly to it: void insert(struct TrieNode *root, string key) { struct TrieNode *pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) pCrawl->children[index] = getNode(); pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isEndOfWord = true; }
I don't think pCrawl is needed. The argument root is a copy of what is passed and modifying that won't affect the caller, so it is free to modify the value of root in the function. It may be for clarity gained by using clear names for the argument (for input) and variable (for processing).
73,041,146
73,041,247
Linux gRPC & Conan Version incompatibility
I am trying to use gRPC to create a simple rpc mechanism for a project. I started by cloning gRPC from github and selecting the tag for version 1.47.1. I built and installed this on Ubuntu as per the instructions, by pulling from GitHub and selecting the tag for v1.47.1 I then created a simple file, e.g. // Latest proto standard syntax = "proto3"; package packageName; // TODO Define service name service ConfigService { rpc GET (GetRequest) returns (GetResponse); } message GetRequest { string id = 1; } message GetResponse { string value = 1; } Next step is to generate the C++ code GEN_GRPC_SERVER_DIR=./gen_grpc_server_base GEN_GRPC_MESSAGE_DIR=./gen_grpc_message_defs mkdir -p $GEN_GRPC_SERVER_DIR $GEN_GRPC_MESSAGE_DIR protoc --proto_path=. --cpp_out=$GEN_GRPC_MESSAGE_DIR \ --grpc_out=$GEN_GRPC_SERVER_DIR \ --plugin=protoc-gen-grpc=/usr/bin/grpc_cpp_plugin \ ./simple.proto I am using CMake with Conan to build. My conanfile.txt includes the line: grpc/1.47.1 Unfortunately when I try and build it using CMake with Conan I get an error about versioning. Which is triggered by the following generated code: #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3019000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3019004 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif When I checked the file port_def.inc in the clone of grpc from github it shows that the version is 301900 When I check the version reported from the file port_def.inc from my ~/.conan/data/grpc directory is 3021000 hence the error message. I assumed the version would match because my Conan file states the version as 1.47.1 and the tag of gRPC from GitHub I selected is v1.47.1. Further investigation of the GitHi clone reveals that the file port_def.inc comes from the the submodule for protobuf. The tag for protobuf that has a version of port_def.inc whcih has the correct version is tagged v3.21.0 which is not the version used by gRPC v1.47.1 How do I pull and build a version of gRPC from GitHub which matches the version used by Conan? or is there a better approach?
You can either override the protobuf version in your conan recipe to 3.19.4 or probably better to update the git submodule in grpc/third_party/protobuf to 3.21.0: cd grpc/third_party/protobuf git checkout v3.21.0
73,042,171
73,042,767
why add_subdirectory() command did not work for my CMakeLists.txt?
I have a simple exercise on cmake with following file tree: proj01/ include/ functions.h src/ main.cpp functions.cpp CMakeLists.txt CMakeLists.txt README My project CMakeLists.txt is like this: cmake_minimum_required(VERSION 3.21) project (test01) add_subdirectory(src) set(SOURCES main.cpp functions.cpp ) add_executable(myProgram ${SOURCES}) and when I tried to build, I got error: # Error! CMake Error at CMakeLists.txt:18 (add_executable): Cannot find source file: main.cpp CMake Error at CMakeLists.txt:18 (add_executable): No SOURCES given to target: myProgram If I change the project CMakeLists.txt by giving the absolute path(relative to the project), it worked! #add_subdirectory(src) set(SOURCES src/main.cpp src/functions.cpp ) add_executable(myProgram ${SOURCES}) When there is multiple source files in multiple subdirectories, it would be better to explicitly list all source files including their paths as what is done with my working version of the CMakeLists.txt. Spent hours to search for command add_subdirectories(), this, this, and this, but no luck. The closest one would be this question, but there is no solution for that question so far. What did I miss with my add_subdirectory(src) in this simple specific scenario? Any help is appreciated.
add_subdirectory(src) results in cmake parsing src/CMakeLists.txt creating a new directory src in the build tree for building the part of the project in this cmake file. It doesn't result in you being able to use shorter paths in the CMakeLists.txt file containing the add_subdirectory command. If you move the target to src/CMakeLists.txt you could use the shorter paths: CMakeLists.txt cmake_minimum_required(VERSION 3.21) project (test01) add_subdirectory(src) # add src/CMakeLists.txt to this project src/CMakeLists.txt cmake_minimum_required(VERSION 3.21) set(SOURCES main.cpp functions.cpp ) add_executable(myProgram ${SOURCES}) Personally I'd avoid adding an additional CMakeLists.txt file just to shorten the paths. It's easy to remove the duplication of the src dir, if that's what you're worried about. set(SOURCES main.cpp functions.cpp ) list(TRANSFORM SOURCES PREPEND "src/") or function(subdir_files VAR DIR FILE1) set(FILES) foreach(SRC IN ITEMS ${FILE1} ${ARGN}) list(APPEND FILES ${DIR}/${SRC}) endforeach() set(${VAR} ${FILES} PARENT_SCOPE) endfunction() subdir_files(SOURCES src main.cpp functions.cpp )
73,042,277
73,042,393
How to use a char after the double colons of enum that resolves to one of the enum's values
I'm reading values from an input text file that I have no control over. The first line is an integer representing the number of the lines to follow. Each of those lines to follow contains one of 3 characters that can be found in the next enum: enum Size { S, M, L } The ifstream can't insert the value directly into a Size datatype. So the following code won't work to store all the values in a vector of the datatype Size enum Size { S, M, L } unsigned lines_count; std::vector<Size> data; file >> lines_count; for (auto i = 0u; i < lines_count; ++i) file >> data[i]; // WRONG So the values have to be stored into a char. I was wondering if there was a way to store the value into the datatype Size directly that RESEMBLES the following: unsigned lines_count; Size size; char c; file >> lines_count; for (auto i = 0u; i < lines_count; ++i) { file >> c; size = Size::c // c resolves to either S, M, or L data[i] = size; } I know that this syntax does NOT work. I just need the most concise way to do it instead of using a switch or if-statements.
Enumerations have an underlying integral type with which the enumerators are represented. You can specify which integral value each enumerator should have explicitly. Since character literals are just integral values, you can specify them as well. Then you can simply cast from any integral type to the enumeration type to get the enumerator corresponding to the integral value. This is not an implicit conversion and therefore requires an explicit static_cast. It does however not check in any way that the values are actually validly one of the enumerators. Especially if you go out-of-range of the enumeration range, you can cause undefined behavior if not checking beforehand or you could be using a value inside the range which doesn't match any of the enumerators. So you probably won't get around writing a function which manually checks the value anyway to have proper input validation. I would also use a scoped enumeration since C++11. You can also explicitly specify that the underlying type shall be char, then at least there are no range issues as mentioned above: enum class Size : char { S = 'S', M = 'M', L = 'L' }; //... file >> c; // Does not validate that the value of c is one of the above! data[i] = static_cast<Size>(c);
73,042,385
73,042,579
Project Euler #10 [C++] sum of primes below 2000000
Prompt: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. Code: #include <iostream> #include <list> /** * @brief Searches for numbers that in a that can be factored by b * * @param a list of numbers * @param b factorable number */ void search(std::list<long long>& a, long long b, std::list<long long>::iterator c); int main() { std::list<long long> nums; long long range = 0; long long PrimesSum = 0; std::cout << "Sum all the primes up to: "; std::cin >> range; for (int i = 2; i <= range; i++) { nums.push_back(i); } for (std::list<long long>::iterator it = nums.begin(); it != nums.end(); it++) { search(nums,*it,it); } for (std::list<long long>::iterator it = nums.begin(); it != nums.end(); it++) { PrimesSum+=*it; } std::cout << "The sum of all primes below " << range << " is " << PrimesSum << ".\n"; } void search(std::list<long long>& a, long long b, std::list<long long>::iterator c) { std::list<long long>::iterator it = c; while (it != a.end()) { if (*it % b == 0 && *it != b) { a.erase(it); } it++; } } Problem: I am getting a segmentation fault for values above 46998. Anything equal to or less than 46998 will work as expected. Could I get some help as to what I'm doing wrong or what I can improve?
In fact there is no need to define a list to calculate the sum of prime numbers. Nevertheless if to use your approach then within the function search after the statement a.erase(it); the iterator it becomes invalid. You should write while (it != a.end()) { if (*it % b == 0 && *it != b) { it = a.erase(it); } else { it++; } } Or you could write ++it; while (it != a.end()) { if (*it % b == 0) { it = a.erase(it); } else { it++; } } Pay attention to that instead of this for loop for (std::list<long long>::iterator it = nums.begin(); it != nums.end(); it++) { PrimesSum+=*it; } you could use standard algorithm std::accumulate declared in the header <numeric> PrimesSum = std::accumulate( nums.begin(), nums.end(), 0ll ); Using the approach with a list I would write the program the following way #include <iostream> #include <list> #include <iterator> #include <algorithm> #include <numeric> int main() { unsigned int range = 10'000; std::list<unsigned int> primes; for ( unsigned int i = 1; i++ < range; ) { if ( std::find_if( std::begin( primes ), std::end( primes ), [&i] ( const auto &item ) { return i % item == 0; } ) == std::end( primes ) ) { primes.push_back( i ); } } auto sum = std::accumulate( std::begin( primes ), std::end( primes ), 0llu ); std::cout << "There are " << primes.size() << " prime numbers.\nTheir sum is " << sum << '\n'; } The program output is There are 1229 prime numbers. Their sum is 5736396
73,043,451
73,043,650
Upcasting through std::any
In C++ you can pass instances of Derived to functions accepting Base, if Base is a base class of Derived. This is very useful for satisfying APIs and a very common design pattern for APIs. Currently I am faced with a situation, where I want to upcast through an std::any. That is I have an std::any that stores an instance of Derived and I would like to cast its address to a pointer to Base in an API function, that should not know of the existence of Derived. My use case is a runtime reflection library that passes around std::anys storing instances of the reflected types. I understand that upcasting through std::any is not possible, because std::any_cast checks the typeid before casting and returns a nullptr if the types don't match, see cppreference. But maybe there is a workaround or some clever trick that I could use? It feels like it must be possible somehow, as upcasting is such a common thing in C++ and the std::any has the address and type I need. Here is a code example. The following code segfaults as expected because the std::any_cast returns a nullptr in any_function which is dereferenced in the following line. Compiler explorer: https://godbolt.org/z/E9sG9G3ff #include <any> #include <iostream> class Base { public: double get_val() const { return val; } private: double val {1.23}; }; void normal_function(Base const& b){ std::cout << b.get_val() << std::endl; }; void any_function(std::any const& b){ auto* ptr = std::any_cast<Base>(&b); std::cout << ptr->get_val() << std::endl; } class Derived : public Base {}; int main() { Derived d; // normal upcasting normal_function(d); // upcasting thru std::any std::any ad = d; any_function(ad); return 0; }
any is a type-safe void*. That means it obeys the rules of a void*. Namely, if you cast a T* to a void*, the only type you can cast it back to is T*. Not to a U* where U is a base class of T. It must be exactly and only T*. The same goes for any. any (like this use of void*) is for situations where code A needs to communicate with code C, through some intermediary B. A and C agree on what type is involved, but B doesn't need to know what type is being communicated (perhaps because B facilitates transactions between many different pairs of As and Cs). Agreeing on what type is involved means the exact type that is involved. If A is communicating with code that only takes a base class, then that's what it needs to provide (by storing a pointer to the base class of its derived class instance). Now, the general idea of what you're asking for is not unreasonable. However, implementing it is... difficult. Most forms of type erasure can handle types that have similar behavior, but the behavior of the type being erased needs to be known at the time of the erasure, not the time of use of that functionality. If a type needs to be convertible to some type, then exactly what that type is needs to be known when the object is added to the any. That would become part of the interface of the hypothetical any type, and thus it would be baked into its code. It cannot take "any" type and then later ask, "hey, are you convertible to ThisType?"
73,043,455
73,043,534
Function to check if a string is an ANSI escape sequence?
I need a C++ function (or object) able to tell me if a certain string is an ANSI escape sequence. So, if I have for example: std::string ansi = "\033[0m"; I would need something like this: is_escape_char( ansi ) which returns false or true if the string is an ANSI escape sequence. Is it possible?
If you know it's at the start of the string bool is_escape_char(std::string_view str) { return str.starts_with("\033"); } Otherwise look for it anywhere in the string bool is_escape_char(std::string_view str) { return std::string_view::npos != str.find("\033"); } Depending on what you need, you can capture the index in the return of 'find', determine which sequence it is, and find the next code that finishes the sequence. But it requires inspection of the characters following the initial escape.
73,044,313
73,048,238
How to avoid code copying in this class hierarchy?
I have the following class hierarchy, in which the instantiation of class B has to be static in both child classes: #include <iostream> class A { protected: virtual int get_num() const=0; }; class B { int num; public: int get_num() { return num=2; } }; class D1 : public A { public: static B b; int get_num() const override { return b.get_num(); } }; B D1::b; class D2 : public A { public: static B b; int get_num() const override { return b.get_num(); } }; B D2::b; int main() { D1 d1; std::cout << d1.get_num() << std::endl; D2 d2; std::cout << d2.get_num() << std::endl; return 0; } My problem is that the definitions of the getter functions in the children classes are CTRL+C CTRL+V copies of each other, which should be avoided because they do exactly the same and they might be lengthy. I am looking for a possible workaround, is there a better practice in such a case? Is this a code smell and a sign of bad design? Edit: Classes D1 and D2 (and all their derived classes) can do different things, but the point is that the objects of the classes of each branch in the hierarchy have to work on the same instantiation of B (that's why it is declared as static). Otherwise, B could be instantiated in A. The problem is that the functions (which do the same and could be defined in A in the latter case) in the lack of instantiation of B in A, have to be defined in D1 and D2.
If you have several classes that all have a B member and delegate some functionality to it, you should extract this bit into a common base class. If it is not a static member you would do just this: class Awith B : public A { public: int get_num() override { return b.get_num(); } private: B b; }; Now your D1 and D2 can inherit AwithB without even knowing that B exists. If they do need to know about B for some other reason, just change private: to protected:. Now if the B object should be static, and each derived class should have its own separate instance, this is a bit trickier, but not by much. template <typename Derived> class AwithB : public A { ... static inline B b; }; class D1 : public AwithB<D1> { ... }; class D2 : public AwithB<D2> { ... }; Here we use CRTP to inject the derived class identity to the base. Different derived classes derive from different specializations of AwithB, so each has its own static member.
73,044,391
73,045,469
Overload macro as variable and function
First, there are a lot of posts on overloading macros: Can macros be overloaded by number of arguments? C++ Overloading Macros Macro overloading Overloading Macro on Number of Arguments etc. ... However, all of them ask the question about variadic macros. What I'd like to ask is if the following is possible: #define FOO 3 #define FOO(a,b) a+b int main() { int a = FOO(0,1); int b = FOO; std::cout << a + b; return 0; } I'd like for it to work on clang as well.
It's not a macro, but looks like it struct SmartMacro { constexpr operator int() const noexcept { return 3; } constexpr int operator()(int a, int b) const noexcept { return a + b; } }; constexpr SmartMacro FOO; int main() { int a = FOO(0,1); int b = FOO; std::cout << a + b; return 0; }
73,044,484
73,045,387
MSVC won't perform a user-defined implicit conversion to std::nullptr_t when invoking operator==
Consider the following piece of code: struct X { operator std::nullptr_t() const { return nullptr; } }; X x; assert(x == nullptr); As far as I can tell, it should work because X is implicitly convertible to std::nullptr_t and hence operator== should perform that implicit conversion to the left argument. This seems to be what happens in GCC and Clang, which happily accept the code. CppInsights seems to confirm that the implicit conversion indeed takes place as expected. However, this code fails to compile in MSVC with the following error (Godbolt link) error C2676: binary '==': 'main::X' does not define this operator or a conversion to a type acceptable to the predefined operator Is this code invalid, implementation specific behavior, or is MSVC wrong for rejecting it?
MSVC is wrong in rejecting the code since the program is well formed as the implicit conversion via the conversion operator can be done for the check x == nullptr. A bug report for the same has been submitted here.
73,044,691
73,044,849
How boost format works in terms of c++?
I was looking at boost::format documents and just the first example made me wondering: cout << boost::format("writing %1%, x=%2% : %3%-th try") % "toto" % 40.23 % 50; What does it mean in terms of c++? I can understand call to boost::format itself, there's nothing strange there, but what's the meaning of the rest? % "toto" % 40.23 % 50 Am I missing some special meaning '%' has in c++? What does this mean in terms of the language? I had a look into headers, but they're not particularly readable to be honest)
%, like many operators in C++, can be overloaded for arbitrary types. If we have the expression a % b where a is of type A and b is of type B, then C++ will look for functions compatible with the following signatures. R operator%(const A& a, const B& b); R A::operator%(const B& b) const; So, presumably, boost::format returns some custom class, on which operator% is defined. The operator% defined there takes this custom class and a string and produces a new instance of this custom class. Finally, when we std::cout << ... the custom class, Boost provides an overload for that as well which prints out the string representation. If we remove all of the operators and pretend everything is ordinary method calls, effectively this cout << boost::format("writing %1%, x=%2% : %3%-th try") % "toto" % 40.23 % 50; becomes pipe(std::cout, percent(percent(percent(boost::format(...), "toto"), 40.23), 50)); And overload resolution on the names pipe and percent takes care of the rest.
73,044,955
73,045,022
How do I find out entry-point function in C++ dll project?
I built one project from GitHub. The project was built successfully, but I can't find the entry-point function in its code. The project settings are like this: How do I find out the entry-point function in a C++ DLL project?
Per /ENTRY (Entry-Point Symbol): By default, the starting address is a function name from the C run-time library. The linker selects it according to the attributes of the program... Unless specified differently, the entry point for a DLL in a MSVC++ project is _DllMainCRTStartup(), which calls DllMain() in the project's code, if it exists. See DLLs and Visual C++ run-time library behavior on MSDN for more details.
73,045,075
73,045,216
Why a portion of my Array output a value different from what i extracted(c++)?
data11.txt: Length(l) Time(t) Period(T) 200 10.55 0.527 300 22.72 1.136 400 26.16 1.308 500 28.59 1.429 600 31.16 1.558 ill be taking data from this file above in my code #include <iostream> #include <cmath> #include <fstream> #include <string> #include <iomanip> /*Using data11.txt as reference, write code to read from the file. In a pendulum experiment certain data was recorded in order to calculate the acceleration due to gravity. All calculations should be in their SI units Write a function to calculate the acceleration due to gravity as the slope of the graph to this equation.T=2πlg−−√. What is the percentage error in your calculated value? Take g=9.8ms-2. If the pendulum weighs 50g and is displaced at an angle of 30, what will it maximum kinetic energy value for each length of the string? Display your answer in table form. */ using namespace std; double slope_gravity(double T1, double T2, double L1, double L2){//slope function double T1_inverse = 1/pow(T1,2); double T2_inverse = 1/pow(T2,2); double difference_T = T2_inverse - T1_inverse; double difference_L = (L2 - L1)/100; double slope = (difference_T/difference_L); return slope; } const int n = 4; int main (){ ifstream mydata; string capture; float Length[n], Time[n], Period[n], acc_gravity;//declaring variable mydata.open("Data11.txt"); if (mydata.is_open()){ for (int i=0; i<n+1; i++){ getline(mydata, capture); mydata >> Length[i] >> Time[i] >> Period[i]; } acc_gravity = slope_gravity(Period[1], Period[0], Length[1], Length[0]);//acceleration due to gravity calc cout << fixed << showpoint << setprecision(1); cout << "The Acceleration Due To Gravity Obtained Experimentally " << "from the data11 file is "<<abs(acc_gravity)<<"ms^-2"<<endl; cout << "Calculating for Percentage error............."; cout <<endl<<endl; float percent_error = (abs(acc_gravity)- 9.8) * 100/9.8;//error analysis cout << "Percent Error is "<< setprecision(2) << abs(percent_error)<<"%"<<endl; cout << endl; cout << "Calculating Max Kinetic Energy of pendulum weighing 50g being " << "displaced at an angle of 30\n"; cout << setprecision(4); float velocity[n], x[n], y;//kinetic energy calc double max_KE[n]; for (int j=0; j<n+1; j++){ x[j] = 2 * acc_gravity * Length[j]/100; y = 1 - cos(30); velocity[j] = sqrt(x[j] * y); max_KE[j] = 0.5 * 50/1000 * pow(velocity[j],2); } cout<<endl<<endl; cout << setprecision(1); cout << "Length(m)\tMaximum Kinetic Energy(J)\n";//tabular form display for (int k=0; k<n+1; k++){ cout << Length[k] <<"\t"<< max_KE[k] <<endl; } } mydata.close(); return 0; } The objective of the program is in the first comment above. At the end of the program, i'm supposed to print the values of length and Maximum Kinetic energy to the console in a tabular form. However, in the array Length[0], it prints 31.16, but i extracted data from data11.txt, so there is supposed to be the value 200 instead. The origin of the problem start with this for loop. The for loop works well by extracting values from data11.txt. so the value of Length[0] is 200 here. i've tried to check why it is behaving this way. The problem starts here; mydata.open("Data11.txt"); if (mydata.is_open()){ for (int i=0; i<n+1; i++){ getline(mydata, capture); mydata >> Length[i] >> Time[i] >> Period[i]; } But outside the forloop, Length[0] is 31.16. I also noticed that Time[4] has different value from input value which is supposed to be 31.16. Please any help with this?
What you have noticed is called 'buffer overrun'. float Length[n], Time[n], Period[n], acc_gravity; // since 'n' is 4, // so the valid range of subscript of Length/Time/Period are [0-3] // That means, if you try to write to Length[4], // that is invalid, often lead to ruin something else. mydata.open("data11.txt"); if (!mydata.is_open()) { fprintf(stderr,"failed to open datafile.\n"); return 1; } for (int i=0; i<n+1; i++){ // here the rang of 'i' is [0 - 4] getline(mydata, capture); mydata >> Length[i] >> Time[i] >> Period[i]; // so, when i==4, // 'buffer overun' happens here. // 'Time' could be ruined by 'Period'. } If you want to skip the 'header' line of input file, one possible approach is : "'getline()' once , then enter the loop". Whatever you choose, just don't 'buffer overrun'. Good luck.:)
73,045,134
73,045,205
SetWindowText with a String and Integer
I'm running a threaded application and monitoring the duration with chrono. What I'm trying to do is then set the window title to say "Duration: " + the time taken. This is what I have so far but it just makes the window title blank. // Calculate Duration int duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count(); // Update the window title std::string windowText = "Duration: " + duration; SetWindowText(_hwnd, (LPCWSTR)windowText.c_str());
First, there's an issue where you're using pointer arithmetic and expecting string concatenation plus integer-to-string conversion. The value "Duration: " + duration is going to be a pointer that is offset from the start of the "Duration: " string literal by duration bytes. If that is any value outside the range [0,10] then you'll have undefined behavior. In any case, that's not what you're looking for. You can instead do this: std::string windowText = "Duration: " + std::to_string(duration); Second, you also have a problem with the call to SetWindowText which requires a wide string. You are attempting to cast it, but that is invalid. No character conversion takes place. You need to convert the string, OR just use wide strings to begin with: std::wstring windowText = L"Duration: " + std::to_wstring(duration); SetWindowText(_hwnd, windowText.c_str());
73,045,566
73,045,621
How to retrieve the new integer data after completion of a call to Document().Set(MapFieldValue{string_key, Increment()}) in Firestore C++
I'm attempting to atomically increment integer values in Firestore and read the value on the client side after the Set() operation is complete on the server side, with the guarantee that another Set() call won't overwrite the value on the server before the value is retrieved for the client. Without this guarantee it seems that there could be a chance of unwanted data duplication. However, I can't seem to find a means to guarantee this in my code. Here's what I've written so far: doc_ref.Get().OnCompletion([this, ref_name](const firebase::Future<firebase::firestore::DocumentSnapshot>& future) { if (future.error() == 0) { const firebase::firestore::DocumentSnapshot& document = *future.result(); db->Collection("collection_name").Document(ref_name).Set({ ref_name, firebase::firestore::FieldValue::Increment(1) }) .OnCompletion([this, ref_name](const firebase::Future<void>& void_future) { dr_uc.Get().OnCompletion([this, ref_name](const firebase::Future<firebase::firestore::DocumentSnapshot>& new_future) { if (new_future.error() == 0) { const firebase::firestore::DocumentSnapshot& new_document = *new_future.result(); int user_name_count = new_document.Get(ref_name).integer_value(); } }); }); } }); The call to firebase::firestore::FieldValue::Increment(1) guarantees that the integer value will be updated atomically on the server side but the Get() call doesn't appear to guarantee a read from the server which hasn't been written to by another Set() call prior to the data being retrieved. Is there some means to provide this guarantee using Firebase's Firestore?
The increment operator does nothing more than ensure the increment happens atomically on the server, and does not involve any transfer of values to/from the client. If you want full control over the order of the operations, including the read, you probably want to use a transaction to accomplish that.
73,045,735
73,047,277
Intuition on C++ situations where an an unknown number of objects of a custom class will be needed at runtime
Everything below has to do with situations where a developer makes a custom C++ class (I have in mind something like OnlyKnowDemandAtRuntime below)... and there can be no way of knowing how many instances/objects "the user" will need during runtime. Question 1: As a sanity check, is it fair to say that in Case One below, RAII is being used to manage the "dynamic" usage of OnlyKnowDemandAtRuntime? Question 2: Is it correct to say that in case two, RAII isn't the first option that comes to mind simply because it is inconvenient (possibly a major understatement here) to hack up a way to wrap the nodes of a tree in an STL container? And, therefore, it is simpler to just use new and destructor/delete (or smart pointers) here, rather than scramble for a way to have the standard library manage memory for us. Note: Nothing here is a question about whether trees are often used in day to day work; rather, everything in this post is about the intuition behind the decision making one must do when using C++ to create objects at runtime. Note: Of course smart pointers are themselves part of the library, and of course they handle memory for us just as the library containers do... but for the purposes of this question I'm putting smart pointers and new on the same footing: Because my question is about the limits on the abilities of the STL containers to have more and more instances of something like OnlyKnowDemandAtRuntime inserted into them at runtime, while also being able to handle the relationships between said instances (without adding lots of logic to keep track of where things are in the container). Question 3: If 1 and 2 are reasonable enough, then would a fair summary be this: [When a developer makes a custom class but doesn't know how many objects of it will be needed during runtime], either... Wrap the objects in an STL container when the structure between said objects is "trackable" with the STL container being used (or perhaps trackable with the STL container being used plus some reasonably simple extra logic), or Explicitly use the heap to build the objects with new and destructor/delete, or smart pointers, and manually build the structure "between" said objects (as in left_ and right_ of Case Two below). Quick reminder, this isn't about whether we need to build trees in day to day work with C++. Also, (and I suppose this is already clear to anyone who would answer this question) this is not about "use the heap when an object is too big for the stack or when an object needs a lifetime beyond the scope in which it was created". Case One: // This is the class "for" which an unknown of objects will be created during runtime class OnlyKnowDemandAtRuntime { public: OnlyKnowDemandAtRuntime(int num) : number_(num) {}; private: int number_; }; // This is the class where an a priori unknown number of `OnlyKnowDemandAtRuntime` objects are created at runtime. class SomeOtherClass { public: void NeedAnotherOnlyKnownAtRuntime(int num) { v_only_know_demand_at_runtime_.emplace_back(num); } private: std::vector<OnlyKnowDemandAtRuntime> v_only_know_demand_at_runtime_; } Case Two: // This is the class "for" which an unknown of objects will be created during runtime class Node{ public: Node(int value) : value_(value), left_(nullptr), right_(nullptr) {}; private: int value_; Node *left_; Node *right_; friend class Tree; }; // This is the class where an a priori unknown number of `Node` objects are created at runtime. class Tree { public: ~Tree() { // Traverse tree and `delete` every `Node *` //} void Insert(int value) { Node *new_node = new Node(value); ThisMethodPlacesNewNodeInTheAppropriateLeafPosition(new_node); } private: Node *root; }
Not to your literal questions but you might find this useful. Smart pointers like std::unique_ptr are most basic RAII classes. Using RAII is the only reasonably sane way to ensure exception safety. In your particular example, I’d use std::unique_ptr<Node> specifically. With arbitrary graph that’d be more complicated ofc. Also, makes a custom C++ class but doesn't know how many objects of it will be needed during runtime. That’s highly unspecific. It is important that you have a container (be it SomeOtherClass or Tree or whatever) that manages these objects. Otherwise, things may become really really complicated.
73,045,806
73,045,864
How to exit the loop :while(cin>>n) in C++
This is a program that counts how many letters and numbers a string has,but when I Press Enter to exit after entering,it has no response. #include <iostream> using namespace std; int main() { char c; int nums=0,chars=0; while(cin>>c){ if(c>='0'&&c<='9'){ nums++; }else if((c>='A'&&c<='Z')||(c>='a'&&c<='z')){ chars++; } } printf("nums:%d\nchars:%d",nums,chars); return 0; }
Pressing enter does not end input from std::cin and std::cin stops when encountering a whitespace. Better would be to use std::getline and std::isdigit as shown below: int main() { int nums=0,chars=0; std::string input; //take input from user std::getline(std::cin, input); for(const char&c: input){ if(std::isdigit(static_cast<unsigned char>(c))){ nums++; } else if(std::isalpha(static_cast<unsigned char>(c))){ chars++; } } std::cout<<"nums: "<<nums<<" chars: "<<chars; return 0; } Demo
73,046,198
73,046,678
How to Store Variadic Template Arguments Passed into Constructor and then Save them for Later Use?
I am curious how one would go about storing a parameter pack passed into a function and storing the values for later use. For instance: class Storage { public: template<typename... Args> Storage(Args... args) { //store args somehow } } Basically I am trying to make a class like tuple, but where you don't have to specify what types the tuple will hold, you just pass in the values through the constructor. So for instance instead of doing something like this: std::tuple<int, std::string> t = std::make_tuple(5, "s"); You could do this: Storage storage(5, "s"); And this way you could any Storage objects in the same vector or list. And then in the storage class there would be some method like std::get that would return a given index of an element we passed in.
Since run will return void, I assume all the functions you need to wrap can be functions that return void too. In that case you can do it like this (and let lambda capture do the storing for you): #include <iostream> #include <functional> #include <string> #include <utility> class FnWrapper { public: template<typename fn_t, typename... args_t> FnWrapper(fn_t fn, args_t&&... args) : m_fn{ [=] { fn(args...); } } { } void run() { m_fn(); } private: std::function<void()> m_fn; }; void foo(const std::string& b) { std::cout << b; } int main() { std::string hello{ "Hello World!" }; FnWrapper wrapper{ foo, hello }; wrapper.run(); return 0; }
73,046,506
73,046,699
Standard library naming convention: Why is the counterpart of std::search called std::find_end?
I was looking at the different algorithms for finding/searching in the standard library and was wondering about the strange naming conventions used. In particular the distinction between the family of search and find algorithms. For example: std::search searches for the first occurrence of a subrange in the input range. In order to find the last occurrence instead, you can use std::find_end. Why is find_end not called search_end? (or search_last). Furthermore: With the exception of find_end, all find* algorithms (find, find_if, find_if_not, find_first_of) look for a single value, whereas the search algorithms look for multiple values (search, search_n). To me this seems like another reason why find_end should be called search_end/search_last. Is there some historical reason for un-intuitive naming of find_end? or is there something else I'm overlooking?
The reason: the algorithms are different. search moves forward by the interval and searches the first occurrence. find_end also moves forward by the interval and finds the last of all occurrences. It uses search and returns the last positive result. Literally, finding is the completion of searching.
73,046,900
73,046,955
C++ set slower than Java TreeSet?
I was working on leetcode problem 792. Number of Matching Subsequences, and one of the initial solutions I came up with was to create a list of ordered sets. Then we can determine if a word is a subsequence of string s by trying to find the ceiling of the next available character of string word using the current index we are in of s. If we can reach the end of word, it is then a subsequence, otherwise, it is not. I know this is not the optimal solution, but what I found surprising was the solution was able to pass in Java, but not with C++(which is significantly slower). I'm still relatively new to C++ and in the process of learning it, so I'm not sure if there is some copying going on, or some other reason why my C++ solution would be much slower? I have tried to change the way I was passing variables, and even tried to remove the isSub() function completely and write the logic in numMatchingSubseq(), however, it was still significantly slower than the Java implementation. Would anyone know why this is? Java Solution class Solution { public int isSub(List<TreeSet<Integer>> alpha, String word) { int N = word.length(); int i = 0, j = 0; while (i < N) { TreeSet<Integer> st = alpha.get(word.charAt(i++) - 'a'); Integer e = st.ceiling(j); if (e == null) return 0; j = e + 1; } return 1; } public int numMatchingSubseq(String s, String[] words) { List<TreeSet<Integer>> alpha = new ArrayList<TreeSet<Integer>>(); for (int i = 0; i < 26; i++) alpha.add(new TreeSet<Integer>()); for (int i = 0; i < s.length(); i++) alpha.get(s.charAt(i) - 'a').add(i); int ans = 0; for (String word : words) ans += isSub(alpha, word); return ans; } } C++ Solution class Solution { public: int isSub(vector<set<int>>& alpha, const string& word) { int i = 0, j = 0, N = word.size(); while (i < N) { set<int> st = alpha[word[i++] - 'a']; auto it = st.lower_bound(j); if (it == st.end()) return false; j = *it + 1; } return true; } int numMatchingSubseq(string s, vector<string>& words) { vector<set<int>> alpha(26); int M = s.size(), ans = 0; for (int i = 0; i < M; i++) alpha[s[i] - 'a'].insert(i); for (const auto& word: words) ans += isSub(alpha, word); return ans; } };
There is definitely some copying happening in the C++ version that isn't happening in the Java version. For instance st could be a reference set<int>& st = alpha[word[i++] - 'a'];
73,047,154
73,047,472
initializer_list constructor somehow excluded from std::variant constructor overload set
Help me solve this puzzle: In the following code I have an std::variant which forward declares a struct proxy which derives from this variant. This struct is only used because recursive using declarations are afaik not a thing in C++ (unfortunately). Anyway, I pull in all the base class constructors of the variant which define for each declared variant alternative T template< class T > constexpr variant( T&& t ) noexcept(/* see below */); according to cppreference. I would assume that this means that a constructor for std::initializer_list<struct proxy> as type T is also defined. However, this doesn't seem to be the case. The following code results in an error: #include <variant> using val = std::variant<std::monostate, int, double, std::initializer_list<struct proxy>>; struct proxy : val { using val::variant; }; int main() { proxy some_obj = {1,2,3,2.5,{1,2}}; } CompilerExplorer Clang Error (because gcc doesn't go into much detail): <source>:12:11: error: no matching constructor for initialization of 'proxy' proxy some_obj = {1,2,3,2.5,{1,2}}; ^ ~~~~~~~~~~~~~~~~~ /opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/13.0.0/../../../../include/c++/13.0.0/variant:1434:2: note: candidate template ignored: could not match 'in_place_type_t<_Tp>' against 'int' variant(in_place_type_t<_Tp>, initializer_list<_Up> __il, ^ /opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/13.0.0/../../../../include/c++/13.0.0/variant:1455:2: note: candidate template ignored: could not match 'in_place_index_t<_Np>' against 'int' variant(in_place_index_t<_Np>, initializer_list<_Up> __il, ^ /opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/13.0.0/../../../../include/c++/13.0.0/variant:1424:2: note: candidate template ignored: could not match 'in_place_type_t<_Tp>' against 'int' variant(in_place_type_t<_Tp>, _Args&&... __args) ^ /opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/13.0.0/../../../../include/c++/13.0.0/variant:1444:2: note: candidate template ignored: could not match 'in_place_index_t<_Np>' against 'int' variant(in_place_index_t<_Np>, _Args&&... __args) ^ /opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/13.0.0/../../../../include/c++/13.0.0/variant:1401:7: note: candidate inherited constructor not viable: requires single argument '__rhs', but 5 arguments were provided variant(const variant& __rhs) = default; What I get from this is that the above mentioned constructor taking the variant alternatives T is not considered. Why?
Your proxy class does not have a declared constructor that accepts a std::initializer_list<proxy>. What it has, is a constructor template that accepts any type, T. But for that template to be chosen, the compiler has to deduce the type of T. The braced-init-list {1,2,3,2.5,{1,2}} does not have any inherent type though, so the compiler can't deduce the type T. It's easy to think that a braced-init-list is a std::initializer_list, but that is not the case. There are some special cases where a std::initializer_list will be implicitly constructed from a braced-init-list, but deducing a template type parameter is not one of those cases. You could explicitly construct a std::initializer_list<proxy>, i.e. proxy some_obj = std::initializer_list<proxy>{1,2,3,2.5,std::initializer_list<proxy>{1,2}}; But keep in mind that std::initializer_list only holds pointers to its elements, and it does not extend their lifetimes. All of those proxy objects will go out of scope at the end of the full expression, and some_obj will immediately be holding a std::initializer_list full of dangling pointers. If you need a recursive type, you will almost certainly need to dynamically allocate the recursive children (and remember to clean them up, as well). std::initializer_list is not sufficient for this use case.
73,047,874
73,047,952
heap-use-after-free when using references with 2D vector in C++
I am solving this problem on leetcode: https://leetcode.com/problems/merge-intervals/ When I go to submit my solution, I get the error of AddressSanitizer: heap-use-after-free. More specifically, there is an error of Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) when I hit the line of code currentMergedInterval = mergedIntervals.back(); but I don't understand why. Whenever I modify the 2-D vector mergedIntervals, I make sure to update my vector reference, currentMergedInterval, after mergedIntervals has been modified. So it's not clear to me why this is causing an issue. #include <stdio.h> #include <vector> #include <algorithm> using namespace std; class Solution { public: vector<vector<int>> merge(vector<vector<int>>& intervals) { vector<vector<int>> mergedIntervals(1, intervals[0]); vector<int>& currentMergedInterval = mergedIntervals.back(); int mergedIntervalEnd = 0; int intervalStart = 0; for (size_t i = 1; i < intervals.size(); i++) { mergedIntervalEnd = currentMergedInterval[1]; intervalStart = intervals[i][0]; if (mergedIntervalEnd >= intervalStart) { currentMergedInterval[1] = intervals[i][1]; } else { mergedIntervals.push_back(intervals[i]); currentMergedInterval = mergedIntervals.back(); } } return mergedIntervals; } }; int main() { Solution s = Solution(); vector<vector<int>> v = {{1,3}, {2,6}, {8,10}, {15,18}}; vector<vector<int>> sol = s.merge(v); // Expected output: [[1,6],[8,10],[15,18]] for (vector<int> vec : sol) { printf("%d %d\n", vec[0], vec[1]); } }
References can't be reassigned. Assigning to a reference variable will not change the reference, it will change the object being referenced. Because of this, and because of adding elements to a vector might invalidate all references, pointers or iterators to elements, the two statements mergedIntervals.push_back(intervals[i]); currentMergedInterval = mergedIntervals.back(); could lead to undefined behavior if the reference currentMergedInterval is now invalid. For this specific case it would be better to use iterators or pointers instead of references, since they can be reassigned.
73,048,442
73,103,481
MyProject.dll is not a valid win32 application
I have copied a C++ solution folder written with visual studio 2013 to my Pc and tried to run it (I mean VS Debugging) with VS 2022. the solution Contains 5 projects but I just target one of them so unloaded the rest and set the one as Startup project and this error happened. Error Image Solution file is working well on first pc and project is not a win32 project its x64 (I don't know much from win32 or x64). Unable to start program. [VALUE].dll is not a valid Win32 application error in Visual Studio 2017 According to this question I tried selecting project, setting as startup, repairing VS, installing vcredist_x64 but non helped. After Running, VS make Debug folder in solution Directory not the project "LP_Dll\x64\Debug" (LP_Dll is the solution name) without any .exe file, and the error path is exactly this folder, can it be from that?
Project properties the "Configuration Type" was mistakenly changed to .dll.
73,048,657
73,048,736
Can a base class access a derived class protected member in c++?
I'm trying to get my base class currency. To access and return the string from it's derived class pound. My instructor specifically said it's a non public type (so I'm assuming a protected member would be the best here) and to NOT declare it in the base class. I'm having trouble making a function string getCurtype()to return the string and friending the derived class pound in my base class isn't not dong what I'm expecting it to do. I'm guessing friending my derived class to the base class, doesn't give it access to it's protected members as it's only accisble in the derived class pound? Can someone please suggest me a way to set a getter string getCurType()for my string currencyType = "dollar" as a protected member in my derived class pound? class currency{ friend class pound; string getCurType(){return currencyType;}; void print(){ cout << "You have " << getPound() << " " << getCurType() << endl; } class pound : public currency{ protected: string currencyType = "pound"; } Error: test.cpp:11:34: error: 'currencyType' was not declared in this scope string getString(){return currencyType;}; ^~~~~~~~~~~~ test.cpp:11:34: note: suggested alternative: 'currency' string getString(){return currencyType;}; ^~~~~~~~~~~~ currency
Your design is backwards. Base classes should not need to know about derived classes other than the interface defined in the base. Define the interface you want to use in the base: class currency{ public: virtual string getCurType() = 0; void print(){ cout << "You have " << getCurType() << endl; } }; class pound : public currency{ string currencyType = "pound"; public: string getCurType() { return currencyType; } };
73,048,664
73,048,861
What is QT_TRANSLATE_NOOP_UTF8 for in Qt?
I cannot find any official documentation about QT_TRANSLATE_NOOP_UTF8 macro. How does it works and what is "scope" argument? Is it namespace? And if it is, how to specify nested namespaces?
I've found documentation for it (it is hard to find but it is documented): - Global Qt Declarations | Qt Core 6.3.2 QT_TR_NOOP(sourceText) Marks the UTF-8 encoded string literal sourceText for delayed translation in the current context (class). The macro tells lupdate to collect the string, and expands to sourceText itself. Example: FriendlyConversation::greeting(int type) { static const char *greeting_strings[] = { QT_TR_NOOP("Hello"), QT_TR_NOOP("Goodbye") }; return tr(greeting_strings[type]); } The macro QT_TR_NOOP_UTF8() is identical and obsolete; this applies to all other _UTF8 macros as well. See also QT_TRANSLATE_NOOP() and Internationalization with Qt. Note bold part. So doesn't matter that this is for QT_TR_NOOP it applies also for: - Global Qt Declarations | Qt Core 6.3.2 QT_TRANSLATE_NOOP(context, sourceText) Marks the UTF-8 encoded string literal sourceText for delayed translation in the given context. The context is typically a class name and also needs to be specified as a string literal. The macro tells lupdate to collect the string, and expands to sourceText itself. Example: static const char *greeting_strings[] = { QT_TRANSLATE_NOOP("FriendlyConversation", "Hello"), QT_TRANSLATE_NOOP("FriendlyConversation", "Goodbye") }; QString FriendlyConversation::greeting(int type) { return tr(greeting_strings[type]); } QString global_greeting(int type) { return qApp->translate("FriendlyConversation", greeting_strings[type]); } See also QT_TR_NOOP(), QT_TRANSLATE_NOOP3(), and Internationalization with Qt.
73,048,675
73,076,709
Automate memory search in dump
I have full dump and want to search across custom made doubly linked list of 6+ millions elements. To make is simple consider that element of list contains data that is type integer. Is that way to find (automate) if there is element with specific value. I'm using Visual Studio 2017 Professional, so action "Debug Managed Memory" is not an option.
I have used WinDbg Preview tool to sovlve this. It's free tool made by Microsoft. It can run JavaScript to analyze memory, and probably much more. Template JS code list iteration : "use strict"; function read_next(addr) { return host.memory.readMemoryValues(addr, 1, 8)[0]; } function read_data(addr) { return host.memory.readMemoryValues(addr + 0x10, 1, 8)[0]; } function invokeScript() { let current = 0x123; // hardcoded while(current) { let data = read_data(current); // use data pointer to analize data current = read_next(current); } }
73,048,832
73,049,415
Unable to locate package g++-arm-linux-androideabi
I have a JNI module and I'm trying to cross compile with GitHub action and the org.codehaus.mojo:native-maven-plugin maven plugin, so I wrote the following workflow that worked before I added the installation of the package arm-linux-androideabi-g++ that the docker image can't find: elaborate-native-module: name: Elaborate native module (${{ matrix.os }} ${{ matrix.architecture }}) strategy: fail-fast: false max-parallel: 2 matrix: os: [windows-latest, ubuntu-latest, macOS-latest] java: [18] architecture: [x86, x64] exclude: - os: macOS-latest architecture: x86 runs-on: ${{ matrix.os }} steps: - name: Set up JDK ${{ matrix.java }} uses: actions/setup-java@v3 with: java-version: ${{ matrix.java }} distribution: 'zulu' architecture: ${{ matrix.architecture }} - if: startsWith(matrix.os, 'ubuntu') && startsWith(matrix.architecture, 'x64') name: Set up C/C++ compiler run: | sudo apt update sudo apt-get -y install g++-aarch64-linux-gnu arm-linux-androideabi-g++ - if: startsWith(matrix.os, 'ubuntu') && startsWith(matrix.architecture, 'x86') name: Set up C/C++ compiler run: | sudo apt update sudo apt-get -y install doxygen vera++ zlib1g-dev libsnappy-dev \ g++-multilib - if: startsWith(matrix.os, 'windows-latest') && startsWith(matrix.architecture, 'x86') name: Set up C/C++ compiler uses: egor-tensin/setup-mingw@v2 with: platform: ${{ matrix.architecture }} - uses: actions/checkout@v2 - name: Build native library run: mvn -B clean compile -Dproject_jdk_version=${{ matrix.java }} -DskipTests=true --file ./native/pom.xml - if: startsWith(matrix.os, 'ubuntu-latest') && startsWith(matrix.architecture, 'x64') name: Build native library for aarch64 run: | mvn -B clean compile -Dproject_jdk_version=${{ matrix.java }} -Paarch64-for-unix-x64 -DskipTests=true --file ./native/pom.xml mvn -B clean compile -Dproject_jdk_version=${{ matrix.java }} -Parm-eabi-for-unix-x64 -DskipTests=true --file ./native/pom.xml - if: github.event_name == 'push' && (endsWith(github.event.head_commit.message, 'Releasing new version') || contains(github.event.head_commit.message, 'Generating external artifacts')) name: Push native library run: | git config user.name "${{ github.event.head_commit.committer.name }}" git config user.email "${{ github.event.head_commit.committer.email }}" git pull origin ${{github.ref}} git add . git commit -am "Generated native library on ${{ matrix.os }} ${{ matrix.architecture }}" --allow-empty git push ... But the workflow fails with this message: Fetched 8180 kB in 2s (4256 kB/s) Reading package lists... Building dependency tree... Reading state information... 15 packages can be upgraded. Run 'apt list --upgradable' to see them. Reading package lists... Building dependency tree... Reading state information... E: Unable to locate package arm-linux-androideabi-g++ ... The code line that doesn't work is sudo apt-get -y install g++-aarch64-linux-gnu arm-linux-androideabi-g++: how can I solve?
Try with sudo apt-get -y install g++-aarch64-linux-gnu g++-arm-linux-gnueabi. The related compilation executable is arm-linux-gnueabi-g++
73,049,169
73,049,356
No Member Named Reverse While Using reverse()
class Solution { public: void print (vector<int> array) { for (int i=0;i<array.size();i++) { cout<<array[i]<<" "; } cout<<endl; } vector<int> nsr(vector<int> heights) { int n = heights.size(); vector<int> v(n); stack <pair<int,int>> s; for (int i=0 ;i<n;i++) { if (s.size()== 0) { v.push_back(-1); } else if (s.size()>0 && s.top().first<= heights[i]) { v.push_back (s.top().second); } else if (s.size()>0 && s.top().first >=heights[i]) { while (s.size()>0 && s.top().first>= heights[i]) { s.pop(); } if (s.size() == 0) v.push_back(-1); else v.push_back (s.top().second); } s.push({heights[i], i}); } return v ; } vector<int> nsl(vector<int> heights) { int n = heights.size(); vector<int> v(n); print(v); stack <pair<int,int>> s; for (int i=n-1; i>=0;i--) { if (s.size()== 0) { v.push_back(n); } else if (s.size()>0 && s.top().first<= heights[i]) { v.push_back (s.top().second); } else if (s.size()>0 && s.top().first >=heights[i]) { while (s.size()>0 && s.top().first>= heights[i]) { s.pop(); } if (s.size()== 0) v.push_back(n); else v.push_back (s.top().second); } s.push({heights[i], i}); } // print (v); return v; } int largestRectangleArea(vector<int>& heights) { vector<int> width ; vector <int> left= nsl(heights); left.reverse(left.begin(),left.end()); vector <int> right = nsr(heights); // print(left); // print(right); for (int i = 0 ;i< heights.size()-1;i++) { int element = left[i] - right[i] - 1; width.push_back (element); } int area = INT_MIN; for (int i =0 ;i<heights.size()-1;i++) { int newarea = heights[i]* width[i]; area = max(area, newarea); //cout<< area <<endl; } return area ; } }; I am using reverse() in vector but it's showing an error. I have tried using header files but the error is same. I had used reverse with vector many times but it never gave an error. Error : Line 80: Char 14: error: no member named 'reverse' in 'std::vector<int, std::allocator>' left.reverse(left.begin(),left.end());
There is no member function reverse in the class template std::vector. So this statement left.reverse(left.begin(),left.end()); is invalid. You should use the standard algorithm std::reverse declared in the header <algorithm> as for example reverse(left.begin(),left.end()); There are other problems with your code. For example in this declaration vector <int> right = right(heights); the declared identifier right hides a function right used as an initializer expression. (I suppose that in the right side there is used a call of a function with the name right.) That is in the both sides there is used the vector right. So the declaration does not make a sense. If you mean the vector right in the both sides then just write vector<int> right(heights); Or it is unclear where the name element used in this for loop for (int i = 0 ;i< heigths.size()-1;i++) { element = left[i] - rigth[i] - 1; width.push_back (element); } is declared. Or for example this for loop for (int i =0 ;i<heights.size()-1;i++) { int area = INT_MIN; int newarea = heights[i]* width[i]; area = max(area, newarea); } does not find the maximum area. And moreover outside the loop the name area used in the return statement return area ; is undefined. You need to revise your code entirely from the very beginning.
73,049,388
73,049,460
Problem with remove function while trying to remove a file from directory in C++
I need to remove a file from a directory based on the input of user and pass it into a function that perform the file remover process /* Class 3 veus 3:45PM*/ #include <string> #include <iostream> #include <stdio.h> #include <cstdio> void remove_file(std::string file); int main() { std::string file_name; std::cin >> file_name; remove_file(file_name); } void remove_file(std::string file) { if(remove("C:\\MAIN_LOC\\" + file + ".txt") == 0) { std::cout << "`" << file << "`" << " Item deleted successfully" << std::endl; } else { std::cout << "[Error] File not found"; } } Ok now the thing is I got several error on remove function: function "remove" cannot be called with the given argument list. I'm not sure what the error mean so I'd like for an explanation.
use the function with c string instead: void remove_file(std::string file) { std::string x = "C:\\MAIN_LOC\\" + file + ".txt"; if(remove(x.c_str()) == 0) { .... }
73,050,100
73,050,165
Raw int pointer vs vector::iterator<int>
I was trying to understand difference between a raw pointer and an vector iterator. However, the following program trips me out. Does template function have priority over non-template function? Expected: hello! world! Actual: hello! hello! #include <bits/stdc++.h> using namespace std; template<typename It> void foo(It begin, It end) { cout << "hello! "; } void foo(const int* a, const int* b, size_t n=0) { cout << "world! "; } int main() { vector<int> A = {5,6,7,8,9}; int B[] = {1,2,3,4,5}; foo(A.begin(), A.end()); foo(B, B+5); cout << endl; }
In general iterators of the class template std::vector are not pointers (though in some early versions of compilers they were implemented as pointers). For the both calls there will be called the template function. The call of the non-template function requires conversion to const (qualification conversion). The non-template function would be called if the array was declared with the qualifier const like const int B[] = {1,2,3,4,5}; On the other hand, if you will declare the vector with the qualifier const like const vector<int> A = {5,6,7,8,9}; nevertheless the template function will be called because there will be used objects of the type std::vector<int>::const_iterator that are not pointers to constant objects.
73,050,202
73,050,339
Regex not able to show chars after space
I want to break this string into two parts {[data1]name=NAME1}{[data2]name=NAME2} 1) {[data1]name=NAME1} 2){[data2]name=NAME2} I am using Regex to attain this and this works fine with the above string , but if i add space to the name then the regex does not take characters after the space. {[data1]name=NAME 1}{[data2]name=NAME 2} In this string it breaks only till NAME and does not show the 1 and 2 chars This is my code std::string stdstrData = "{[data1]name=NAME1}{[data2]name=NAME2}" std::vector<std::string> commandSplitUnderScore; std::regex re("\\}"); std::sregex_token_iterator iter(stdstrData.begin(), stdstrData.end(), re, -1); std::sregex_token_iterator end; while (iter != end) { if (iter->length()) { commandSplitUnderScore.push_back(*iter); } ++iter; } for (auto& str : commandSplitUnderScore) { std::cout << str << std::endl; }
A good place to start is to use regex101.com and debug your regex before putting it into your c++ code. e.g. https://regex101.com/r/ID6OSj/1 (don't forget to escape your C++ string properly when copying the regex you made on that site). Example : #include <iostream> #include <string> #include <regex> int main() { std::string input{ "{[data]name=NAME1}{[data]name=NAME2}" }; std::regex rx{ "(\\{\\[data\\].*?\\})(\\{\\[data\\].*?\\})" }; std::smatch match; if (std::regex_match(input, match, rx)) { std::cout << match[1] << "\n"; // match[1] is first group std::cout << match[2] << "\n"; // match[2] is second group } return 0; }
73,050,678
73,051,936
Implementing BlockingQueue using Semaphores only
I'm having a trouble with my code design and can't find a solution. I am implementing a BlockingQueue using Semaphores (TaggedSemaphores, to be precise) without loops, condvars, mutexes, and if-else statements. My current code looks like this: template <typename T> class BlockingQueue { using Token = typename TaggedSemaphore<T>::Token; using Guard = typename TaggedSemaphore<T>::Guard; public: explicit BlockingQueue(size_t capacity): empty_ (capacity), taken_ (0), mutex_(1), put_mutex_(1), take_mutex_(1) { } // Inserts the specified element into this queue, // waiting if necessary for space to become available. void Put(T value) { Guard put_guard (put_mutex_); Token tok (std::move (empty_.Acquire())); Guard guard (mutex_); buffer_.push_back(std::move(value)); taken_.Release(std::move(tok)); } // Retrieves and removes the head of this queue, // waiting if necessary until an element becomes available T Take() { Guard take_guard (take_mutex_); Token tok (std::move (taken_.Acquire())); Guard guard (mutex_); T ret_value = std::move(buffer_.front()); buffer_.pop_front(); empty_.Release(std::move(tok)); return std::move(ret_value); } private: TaggedSemaphore<T> empty_, taken_, mutex_, put_mutex_, take_mutex_; std::deque<T> buffer_; }; The TaggedSemaphore class is a simple wrapper of Semaphore that returns a Token after calling Acquire and invalidates a Token in the Release method. Guard is a RAII-Token, which accepts a TaggedSemaphore instance in it constructor. It stores a valid Token and releases it in the destructor. The issue is that if two threads are simultaneously inserting and retrieving values, then they both modify empty_ and taken_, so in the critical section the threads will be working with wrong data. I am pretty sure that this will cause bugs. However, I can't preemptively lock the mutex_, because it would result in a deadlock, when the queue is either empty or full (thus I lock it in the third line of each function's body). Is there a way to get around this problem?
This queue works fine. put_mutex_ and take_mutex_ are unnecessary, though, and should be removed. You say that simultaneous threads might be "working with the wrong data", but nobody ever gets the value of empty_ or taken_, so they are not working with this data at all. Code like this is difficult to write, and even more difficult to understand when reading it, to the extent that you can verify its correctness. It is vitally important to use comments and names to make that easier. Here is the same code, without the unnecessary mutexes, but with some different names and comments. I think this will make it a lot easier to understand why it's correct. template <typename T> class BlockingQueue { using Token = typename TaggedSemaphore<T>::Token; using Guard = typename TaggedSemaphore<T>::Guard; private: // Number of elements that can be removed without blocking // Always <= queue size TaggedSemaphore<T> avail_; // Number of elements that can be added without blocking; // Always <= queue free space TaggedSemaphore<T> free_; // Mutex to guard access to buffer_ TaggedSemaphore<T> mutex_; std::deque<T> buffer_; public: explicit BlockingQueue(size_t capacity): free_ (capacity), avail_ (0), mutex_(1) { } // Inserts the specified element into this queue, // waiting if necessary for space to become available. void Put(T value) { // there must be space Token tok (std::move (free_.Acquire())); Guard guard (mutex_); buffer_.push_back(std::move(value)); // and now the item is available avail_.Release(std::move(tok)); } // Retrieves and removes the head of this queue, // waiting if necessary until an element becomes available T Take() { // there must be an item available Token tok (std::move (avail_.Acquire())); Guard guard (mutex_); T ret_value = std::move(buffer_.front()); buffer_.pop_front(); // and now there is another free slot free_.Release(std::move(tok)); return std::move(ret_value); } };
73,050,720
73,050,823
What namespace is CWnd in?
My biggest complaint about the MS docs is they don't say what actually contains what class you're looking at. OpenCV is like the gold standard of docs. Tells you the whole function, and what header file it's located in. For those of us that haven't been doing this for 20 years, I don't just know where this is at and it's difficult to google without noise. What namespace is CWnd in?
CWnd being a legacy MFC class, is not defined in any namespace, and therefore considered as belonging to the global namespace. In order to use it you need to #include <afxwin.h>, as you can see in the documentation.
73,050,958
73,051,979
Can I check the actual type of void*?
I have to use a legacy C library in my C++ code. One of the functions of that library looks like this: int legacyFunction(int (*userDefinedPredicateFunction)(void*), void* structure, otherArgs...); This legacyFunction() calls userDefinedPredicateFunction() inside itself passing structure as argument to it. I have multiple custom predicate functions to be used with the above function. Each of these functions works different from the others and expects an argument to be of a strictly defined type to work properly: int userDefinedPredicateFunction1(void* structure) { const expectedType1* const s = reinterpret_cast<expectedType1*>(structure); // Check s conditions... } int userDefinedPredicateFunction2(void* structure) { const expectedType2* const s = reinterpret_cast<expectedType2*>(structure); // Check s conditions... } int userDefinedPredicateFunction3(void* structure) { const expectedType3* const s = reinterpret_cast<expectedType3*>(structure); // Check s conditions... } The problem is that these predicate functions are not safe to use - passing an argument of not the expected type to them will lead to an undefined mess. I need to somehow check the type of the argument and throw if it is not the expected type. structure is not polymorphic, so I cannot use dynamic_cast here. The first thing comes to mind is to use a wrapper function like this one: int legacyFunctionWrapper1(const Type1& structure, otherArgs...) { return legacyFunction( userDefinedPredicateFunction1, &structure, otherArgs...); } This will let structure only to be of a one certain type expected by the predicate function, but a dedicated wrapper function is needed to be written to be used with each predicate function, which is undesirable. Is there more elegant way to check the actual type of void* pointer?
I think you are on the right path with that wrapper function. You can save yourself some work by making it a template. This should work: using legacy_predicate = int (*)(void*); template<class T> void call_legacy(int (*predicate)(T*), T* obj, int otherargs) { using pair_type = std::pair<int(*)(T*), T*>; pair_type realargs = std::make_pair(predicate, obj); legacy_predicate wrapper = +[](void* unsafe) -> int { pair_type& realargs = *static_cast<pair_type*>(unsafe); return realargs.first(realargs.second); }; legacyFunction(wrapper, &realargs, otherargs); } Two things of note: I avoided reinterpret-casting the function pointer since that is technically undefined behavior (though it should work in practice). This introduces some indirection and may be a bit slower The trick is to turn a stateless lambda into a function pointer with the unary + operator To make up for the indirection and maybe modernize the whole thing a bit, consider this: template<class Functor> void call_legacy(Functor predicate, int otherargs) { legacy_predicate wrapper = +[](void* unsafe) -> int { Functor* predicate = static_cast<Functor*>(unsafe); return (*predicate)(); }; legacyFunction(wrapper, &predicate, otherargs); } This allows you to pass arbitrary functors, not just function pointers. So you can use it with lambdas or whatever you want. To get the old pattern, you wrap the object at the call site, maybe make it into a overload. Like this: template<class T> void call_legacy(int (*predicate)(T*), T* obj, int otherargs) { // dispatch to overloaded interface described above return call_legacy([predicate, obj]() -> int { return predicate(obj); }, otherargs); } Warning This only works if legacyFunction does not store the passed void* beyond the runtime of the function. Beware of dangling pointers. Alternative As I've mentioned, casting function pointers is undefined behavior, but it tends to work in simple cases. Rule of thumb: If your platform supports GTK+, it supports simple function pointer casts (because Gtk even does horrible things like changing the number of function arguments). So this is the zero-overhead version: using legacy_predicate = int (*)(void*); template<class T> void call_legacy(int (*predicate)(T*), T* obj, int otherargs) { legacy_predicate unsafe = reinterpret_cast<legacy_predicate>(predicate); legacyFunction(unsafe, obj, otherargs); }
73,051,213
73,051,269
Getting out of bounds error at the runtime without any output
#include <iostream> #include <vector> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); vector<int> v{1, 23, 4, 4, 5, 566, 67, 7, 87, 8, 8}; size_t s = v.size(); for (size_t i = 0; i < s; i++) { cout << v.at(i) << " "; v.pop_back(); } return 0; } In the above code, I am straightaway getting out of bounds error without any output. I expected that it would go out of bounds once it has printed half the vector, but apparently, that's not the case. PS: There are no compile-time errors/warnings. Appreciate any help!
Output is buffered. You can use std::endl or std::cout.flush() to force a flush of the stream: for (size_t i = 0; i < s; i++) { cout << v.at(i) << " "; cout.flush(); v.pop_back(); } PS: As mentioned in comments this code is bound to fail. You iterate till i < s but remove an element in each iteration. I suppose the code is merely to demonstrate the issue of missing output.
73,051,519
73,054,657
Typelist of nested types
I've got a typelist providing the following interface : template <typename... Ts> struct type_list { static constexpr size_t length = sizeof...(Ts); template <typename T> using push_front = type_list<T, Ts...>; template <typename T> using push_back = type_list<Ts..., T>; // hidden implementation of complex "methods" template <uint64_t index> using at; struct pop_front; template <typename U> using concat; template <uint64_t index> struct split; template <uint64_t index, typename T> using insert; template <uint64_t index> using remove; }; In another piece of code, I have such a typelist TL of types statically inheriting a base class providing such an interface : template<typename Derived> struct Expression { using type1 = typename Derived::_type1; using type2 = typename Derived::_type2; }; struct Exp1 : Expression<Exp1> { template<typename> friend struct Expression; private: using _type1 = float; using _type2 = int; }; struct Exp2 : Expression<Exp2> { template<typename> friend struct Expression; private: using _type1 = double; using _type2 = short; }; I want to make the typelist of nested types from TL, something like : using TL = type_list<Exp1, Exp2>; using TL2 = type_list<TL::type1...>; // type_list<float, double> but I can't expand TL as it's not an unexpanded parameter pack. I've thought about index_sequence but can't manage to make it work.
The question is seemingly looking for map, also called transform in C++. TL is one list of types, and the desire is to apply some type-level function (extract ::type1) and have another list of types. Writing transform is straightforward: template <template <typename> typename fn, typename TL> struct type_list_transform_impl; template <template <typename> typename fn, typename... Ts> struct type_list_transform_impl<fn, type_list<Ts...>> { using type = type_list<fn<Ts>...>; }; template <template <typename> typename fn, typename TL> using type_list_transform = type_list_transform_impl<fn, TL>::type; And then the type-level function: template <typename T> using type1_of = typename T::type1; And combine the pieces to get TL2: using TL2 = type_list_transform<type1_of, TL>; // type_list<float, double> Example: https://godbolt.org/z/b7TMoac5c
73,051,801
73,053,396
extern c template instantiation
I want to write a templated function and explicitly instantiate it inside extern "C" block to avoid code duplication. Here is example of what I mean: template<typename T> // my templated function T f(T val){ return val; } extern "C"{ int f_int(int val) = f<int>; // this does not compile, but this is what I want to achieve }
int f_int(int val) = f<int>; is not valid(legal) C++ syntax. The correct syntax to instantiate the function template and return the result of calling that instantiated function with val as argument would look something like: template<typename T> // my templated function T f(T val){ return val; } extern "C"{ int f_int(int val) {return f<int>(val);} // this does not compile, but this is what I want to achieve } Demo
73,052,310
73,052,421
Structures with pointers
so I have a structure called Shield that has three pointers in it. I need to fill up with data one of this pointers before hand and I need to access this data inside of a constant loop. The problem that I'm having is that whenever I try and access what should be in my pointers my program crashes. This is my structure struct Shield{ esat::Vec3 *circle; esat::Vec2 *walls; bool *isActive; }; where esat::Vec3 and esat::Vec2 are just structures with floats representing vectors. I initialize my pointers inside of a function that takes as a parameter an Shield object and fill up such pointer data that I need. void InitShield(Shield shield){ shield.circle = (esat::Vec3*) malloc((KVertices + 1) * sizeof(esat::Vec3)); shield.walls = (esat::Vec2*) malloc((KVertices + 1) * sizeof(esat::Vec2)); shield.isActive = (bool*) malloc((KVertices + 1) * sizeof(bool)); float angle = 6.28f / KVertices; for(int i=0; i<KVertices; ++i){ (*(shield.circle + i)).x = cos(angle * i); (*(shield.circle + i)).y = sin(angle * i); (*(shield.circle + i)).z = 1.0f; (*(shield.isActive + i)) = true; } } And then I try and get access to what I supposedly stored in my pointer. void DrawCircle(esat::Mat3 base, esat::Vec2 *tr_points, esat::Vec3 *circle, bool *checkActive){ CheckShield(first_shield); for(int i=0; i<KVertices; ++i){ esat::Vec3 points = esat::Mat3TransformVec3(base, (*(circle + i))); *(tr_points + i) = {points.x, points.y}; } for(int i=0; i<KVertices; ++i){ if((*(checkActive + i)) == true){ esat::DrawSetStrokeColor(color.r, color.g, color.b); esat::DrawLine((*(tr_points + i)).x, (*(tr_points + i)).y, (*(tr_points + ((i+1)%KVertices))).x, (*(tr_points + ((i+1)%KVertices))).y); } } } This is where my program crashes. When I try and access what should be inside my circle pointer the program fails to and crashes. Does anyone know what am I doing wrong? I haven't figured it out yet.
This function accepts an object of the type Shield by value. void InitShield(Shield shield){ That is the function deals with a copy of the value of the passed argument. Changing the copy within the function does not influence on the original object. If you are using C++ then declare the function at least like void InitShield(Shield &shield){ and use the operator new instead of calling malloc directly. If you are using C then declare the function like void InitShield(Shield *shield){ Also it is unclear why you are allocating KVertices + 1 objects as for example shield.circle = (esat::Vec3*) malloc((KVertices + 1) * sizeof(esat::Vec3)); But the following for loop uses only KVertices iterations. for(int i=0; i<KVertices; ++i){
73,052,522
73,052,868
Boolean bitwise and logical operators
I Have two booleans with OR operation between them. According to my understanding, I can use bitwise or logical operators and it will have the same effect: bitwise: bool first = true, second = false; first = first | second; logical: bool first = true, second = false; first = first || second; Is there any difference? What's the better way?
As noted in the comments, you should use logical operators when you're doing logic and bitwise operators when doing bitwise operations. One of the main differences among these is that C++ will short-circuit the logical operations; meaning that it will stop evaluating the operands as soon as it's clear what the result of the operation is. As an example, this code: bool foo() { std::puts("foo"); return true; } bool bar() { std::puts("bar"); return true; } //... auto const res = foo() || bar(); will only output: foo Function bar won't be evaluated as, in this case, evaluating foo is enough to know the result of expression foo() || bar() is true.
73,053,381
73,054,405
Wording of array-to-pointer conversion and undefined behaviour
According to conv.array, array-to-pointer conversion is defined like this (bold emphasis mine): An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion ([conv.rval]) is applied. The result is a pointer to the first element of the array This wording seems to assume that expression, subject to the conversion, refers to an array which is implicitly understood to be the one referred to by emphasized "the array". However, this is not necessarily the case since it's legally possible, e.g., to have lvalue of type T[N] referring to object of type T: int a[5]; auto pa = reinterpret_cast<int(*)[5]>(&a[0]); Now, *pa is lvalue of type int[5], but refers to int object (the first element of a) since during reinterpret_cast pointer-value was unchanged due to int[5] and int being not pointer-interconvertible types. Note that, on the other hand, *std::launder(pa) is an expression of type int[5] referring to int[5] object at the address represented by pa (i.e., a), so array-to-pointer conversion would apply to it in an obvious way if needed, e.g., by subscript operator. However, applying the conversion to *pa (which applies because expression type is appropriate) results in lack of obvious interpretation of what "the array" from above wording means in this case (and, thus, what resulting pointer points to). In this answer (to question about whether T* and T(*)[N] are pointer-interconvertible), where such situation arises, it's interpreted that behaviour is undefined by omission, however as explained above the quoted paragraph does apply and defines behaviour ("The result is" provided regardless of something like "if the expression refers to array", such condition is absent from wording), but meaning of "the array" is unclear. So, is in this case behaviour indeed undefined per current wording contrary to my observations (if yes, why), defined in some non-obvious way (if yes, in which way), the wording is imprecise?
The paragraph is just in general imprecise, in my opinion. It doesn't say what "the array" refers to at all. No array has been introduced before, only array types. I guess it should probably state explicitly that it refers to the array object result of the glvalue, after temporary materialization if applicable. Then I think it should also have a requirement that the type of that result object be similar to that of the original expression type. That way the result object will always be an array object and it can't have a "wrong" type in the same sense as for pointer arithmetic which already applies in a manual &pa[0] "decay". (see [expr.add]/6) But that is my own interpretation of what seems a reasonable interpretation/improvement. I don't think the current wording makes that clear. This is not the only part of the standard with imprecise wording in regard to lvalue type mismatches like this. See for example CWG 2535 for a similar situation with member access, where a similar resolution is suggested.
73,053,479
73,054,502
Python version mismatch even though CMake reports having found the correct version
I'm building some C++ Python extensions for Python 3.10 (using PyBind11) but I'm finding that when trying to import these extensions I get: ImportError: Python version mismatch: module was compiled for Python 3.8, but the interpreter version is incompatible: 3.10.5. I have find_package(Python3 3.10 REQUIRED) in my CMakeLists.txt and I use -DPYTHON_EXECUTABLE:FILEPATH=$(which python) when running cmake. I can confirm that which python points to a Python 3.10 executable. When running cmake part of the output says: Found Python3: /PATH/TO/venv/bin/python3 (found suitable version "3.10.5", minimum required is "3.10") found components: Interpreter and there are no other mentions of finding some other Python version. The compiled files look like module.cpython-310-x86_64-linux-gnu.so. Because of the 310 they can only be imported into a Python 3.10 interpreter sesion. BUT, when I try importing them I get the ImportError I mentioned above. On the other hand, if I manually rename the compiled files to module.cpython-38-x86_64-linux-gnu.so and open up a Python 3.8 interpreter, I'm able to import. How can I fix this? Why are all the clues suggesting that I have built the files correctly when I somehow haven't? Note that I have already tried the solutions from the answers here.
There may have been other factors at play here (like including 3rd party CMake projects) so to fix my problem the first step was to remove those. Then I: changed my find_package(Python3 3.10 REQUIRED) to find_package(Python3 3.10 REQUIRED COMPONENTS Interpreter Development) (see here). User @Tsyvarev also somewhat alluded to this in his comment on my question. installed sudo apt install python3.10-dev (I only had this for Python 3.8). If you're like me and don't understand the difference between sudo apt install python and sudo apt install python-dev see this answer.
73,054,477
73,054,574
Using G++-12 but still c++20 is still not supported
I am using vs code where I run the task in the terminal with following option: g++-12 build active file compiler: /home/linuxbrew/.linuxbrew/bin/g++-12 I am using Ubuntu 20.04 so I installed the g++-12 version using brew and after some manual setup in vs code I make the g++-12 to run the task along with I change the c++ standard to c++20 but still c++20 features are not supported I check the version of c++ by below code: #include<iostream> int main() { if (__cplusplus == 201703L) std::cout << "C++17\n"; else if (__cplusplus == 201402L) std::cout << "C++14\n"; else if (__cplusplus == 201103L) std::cout << "C++11\n"; else if (__cplusplus == 199711L) std::cout << "C++98\n"; else if (__cplusplus == 202002L) std::cout << "C++20\n"; else std::cout << "pre-standard C++\n"; } Output: c++17 I run the below code: #include <iostream> #include <string.h> using namespace std; template <integral T> T add(T a, T b) { return a + b; } int main() { cout << "Add(5, 10): " << add(5, 10) << endl; return 0; } The error occurred for this code is: Executing task: C/C++: g++-12 build active file Starting build... /home/linuxbrew/.linuxbrew/bin/g++-12 -fdiagnostics-color=always -g "/home/abc/Desktop/d drive/c++ (Advance)/c++/concepts/concepts.cpp" -o "/home/abc/Desktop/d drive/c++ (Advance)/c++/concepts/concepts" /home/abc/Desktop/d drive/c++ (Advance)/c++/concepts/concepts.cpp:17:11: error: 'integral' has not been declared 17 | template <integral T> | ^~~~~~~~ /home/abc/Desktop/d drive/c++ (Advance)/c++/concepts/concepts.cpp:18:1: error: 'T' does not name a type 18 | T add(T a, T b) | ^ /home/abc/Desktop/d drive/c++ (Advance)/c++/concepts/concepts.cpp: In function 'int main()': /home/abc/Desktop/d drive/c++ (Advance)/c++/concepts/concepts.cpp:30:31: error: 'add' was not declared in this scope 30 | cout << "Add(5, 10): " << add(5, 10) << endl; | ^~~ Build finished with error(s). * The terminal process terminated with exit code: -1. * Terminal will be reused by tasks, press any key to close it.
According to https://gcc.gnu.org/onlinedocs/gcc-12.1.0/gcc.pdf g++ 12.1 is defaulting to -std=gnu++17. The default, if no C++ language dialect options are given, is ‘-std=gnu++17’. If you want C++20 you must specify -std=c++20 or -std=gnu++20 on the command line.
73,055,023
73,059,923
`glog` example is not showing output as expected
I am trying to understand glog and therefore trying to run the example code on their github page. I have installed glog (version - 0.6.0) and its dependency gflags (version - 2.2) on my mac OS (10.15.7) I compile the example below #include <glog/logging.h> int main(int argc, char* argv[]) { // Initialize Google’s logging library. google::InitGoogleLogging(argv[0]); // test with setting a value for num_cookies int num_cookies = 3; // ... LOG(INFO) << "Found " << num_cookies << " cookies"; } using the following command (and it compiles without any errors or warnings). g++ glog-test.cpp -I/usr/local/include -L/usr/local/lib -lglog -lgflags -o glog-test.o When I run the example using the following command, ./glog-test.o --logtostderr=1 --stderrthreshold=0 I expect to see the message Found 3 cookies on my terminal, but I see nothing being printed. I have also experimented with different values for logtostderr (0, 1) and stderrthreshold (0, 1, 2, 3) and nothing gets written to the directory or gets printed on the terminal. Any help in understanding what I am doing wrong here would be much appreciated, thank you!
You have to parse the command line flags manually through gflags::ParseCommandLineFlags #include <glog/logging.h> #incldue <gflags/gflags.h> int main(int argc, char* argv[]) { // Initialize Google’s logging library. google::InitGoogleLogging(argv[0]); gflags::ParseCommandLineFlags(&argc, &argv, true); // test with setting a value for num_cookies int num_cookies = 3; // ... LOG(INFO) << "Found " << num_cookies << " cookies"; }
73,055,463
73,056,807
Is it possible to make file accesible ONLY for certain processes?
So I'm attempting to make file accesible only for certain process, firstly by finding it via this function: bool GetProcessSid(PSID* pSID) { PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &entry) == TRUE) { while(Process32Next(snapshot, &entry) == TRUE) { const char* process_name = "testfileaccess2.exe"; std::string t(process_name); std::wstring w_process_name(t.begin(), t.end()); if (w_process_name.compare(entry.szExeFile)== 0) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); //... GetSecurityInfo(hProcess,SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION,pSID,NULL,NULL,NULL,NULL); //getsecurityinfo(hprocess,SE_SERVICE) for service CloseHandle(hProcess); return TRUE; } } } return FALSE; } Works fine, always finds process if its alive and returns pSID. Then I create file like this: PACL pNewDACL = NULL; PSID process_with_access = NULL; PSID current_user = NULL; DWORD sid_size = SECURITY_MAX_SID_SIZE; SID everyone_sid; DWORD dwRes; if (CreateWellKnownSid(WinWorldSid, NULL, &everyone_sid, &sid_size) == FALSE) { throw std::runtime_error("CreateWellKnownSid() failed: " + std::to_string(GetLastError())); } GetProcessSid(&process_with_access); GetCurrentUserSid(&current_user); EXPLICIT_ACCESSA ea[2]; ZeroMemory(&ea, 2 * sizeof(EXPLICIT_ACCESSA)); ea[0].grfAccessPermissions = ACCESS_SYSTEM_SECURITY | READ_CONTROL | WRITE_DAC | GENERIC_ALL; ea[0].grfAccessMode = DENY_ACCESS; ea[0].grfInheritance = NO_INHERITANCE; ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[0].Trustee.ptstrName = reinterpret_cast<char*>(process_with_access); ea[1].grfAccessPermissions = ACCESS_SYSTEM_SECURITY | READ_CONTROL | WRITE_DAC | GENERIC_ALL; ea[1].grfAccessMode = GRANT_ACCESS; ea[1].grfInheritance = NO_INHERITANCE; ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[1].Trustee.ptstrName = reinterpret_cast<char*>(current_user); dwRes = SetEntriesInAclA(2, ea, NULL, &pNewDACL); if (ERROR_SUCCESS != dwRes) { printf("SetEntriesInAcl Error %u\n", dwRes); //TODO: goto Cleanup; } PSECURITY_DESCRIPTOR pSD = NULL; // Initialize a security descriptor. pSD = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH); if (NULL == pSD) { printf("error"); } if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) { printf("error"); } // Add the ACL to the security descriptor. if (!SetSecurityDescriptorDacl(pSD, TRUE, // bDaclPresent flag pNewDACL, FALSE)) // not a default DACL { printf("error"); } SECURITY_ATTRIBUTES sa; // Initialize a security attributes structure. sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = pSD; sa.bInheritHandle = FALSE; HANDLE hFile = CreateFileA(filename, GENERIC_ALL, 0, &sa, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); CloseHandle(hFile); And for now it only sets access for parent of a process, not the process itself. So is it even possible what I am trying to achieve?
No, Windows' security is based around user/group access lists. It would be possible to set up a process so that it was running as some particular user and then restrict access to that user, but any program running as Administrator or Local System would be able to bypass that protection. The best you can do against such programs is to protect against accidental access rather than malicious.