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
74,537,784
74,538,993
Override method for each in parameter pack
I have the following classes: enum class Group { A, B }; template <Group G> class AbstractGroupVisitor; template <Group G> class GroupMessage; class AbstractMessageVisitor; class AbstractMessage { public: virtual void accept(AbstractMessageVisitor& visitor) = 0; }; class AbstractMessageVisitor { public: virtual void visit(GroupMessage<Group::A>& msg) = 0; virtual void visit(GroupMessage<Group::B>& msg) = 0; //A pure virtual method for each item in the Group enum }; template <Group G> class GroupMessage: public AbstractMessage { public: void accept(AbstractMessageVisitor& visitor) final { visitor.visit(*this); } virtual void accept(AbstractGroupVisitor<G>& visitor) = 0; }; Is there a way I can write a CRTP template like the following template <Group... Gs> class GroupsVisitor; That would be able to: Inherit from AbstractMessageVisitor Inherit from AbstractGroupVisitor for every Group in Gs Implement the visit method from AbstractMessageVisitor for every Group in Gs If I were to write a class manually, it would look like: class MyVisitor: public AbstractMessageVisitor, public AbstractGroupVisitor<Group::A>, public AbstractGroupVisitor<Group::B> { public: void visit(GroupMessage<Group::A>& msg) final { msg.accept(static_cast<AbstractGroupVisitor<Group::A>&>(*this)); } void visit(GroupMessage<Group::B>& msg) final { msg.accept(static_cast<AbstractGroupVisitor<Group::B>&>(*this)); } }; As a side note, I am doing this in order to mimic some of the features of virtual inheritance without the overhead of thunks and excess tables for every method in the final class.
You could do some recursion based on template specialization of GroupsVisitor. The following code compiles for me: template <Group... Gs> class GroupsVisitor; template <> class GroupsVisitor<> : public AbstractMessageVisitor {}; template <Group First, Group ... Rest> class GroupsVisitor<First, Rest...> : public AbstractGroupVisitor<First>, public GroupsVisitor<Rest...> { public: void visit(GroupMessage<First>& msg) final { msg.accept(static_cast<AbstractGroupVisitor<First>&>(*this)); } }; class MyVisitor : public GroupsVisitor<Group::A, Group::B> { }; MyVisitor myVisitor; but I had to change AbstractGroupVisitor from being forward declared to have a class body: template <Group G> class AbstractGroupVisitor {}; Otherwise, the compiler complains about "incomplete type".
74,538,802
74,538,862
I am confused a bit in c++...(do-while)
When I compile the program below, the following answer shows up: #include <iostream> int main() { const int COUNT{0}; size_t i{0}; // Iterator declaration do{ std::cout << " I love C++" << std::endl; ++i; // Incrementation }while( i < COUNT); std::cout << "Loop done!" << std::endl; return 0; } I love C++ Loop done! How does the computer calculate 0<0?
The difference between while (condition) do { body }and do { body} while (condition) is that for the latter, the condition is evaluated after executing the body. So the body is guaranteed to execute at least once, and in your example, by the time the condition is checked, i has already been incremented.
74,539,336
74,539,526
Infinite loop from access of improperly created variables
Why does this go into an infinite loop and why does it dump char 0x20? #include <iostream> struct Outer { Outer(std::string &outerString, std::string &superfluousString1, std::string &superfluousString2) : outerString(outerString), inner(*this) {} struct Inner { Inner(Outer &outer) { std::cout << outer.outerString; } } inner; std::string &outerString; }; int main() { std::string outerString("outerString"), superfluousString1("superfluousString1"), superfluousString2("superfluousString2"); Outer outer(outerString, superfluousString1, superfluousString2); return 0; } I discover this whist I was playing around with inner classes. C++ is not main language, and I am coming to this from a long hiatus, so I am asking this to improve my knowledge. I do know that I should not be using the fields of Outer before it has been properly created, so this is a very bad thing to do generally. I feel that the real answer is likely that just because I do not have a compiler error does not mean that something is correct. An interesting side note is that, if I remove either of the superfluous strings, I get a compiler error or it will simply segfault, and that is kind of what I had expected it to do. I boiled this down from a more complex structure that I was playing with, and the elements involved seem to be the minimum required to evoke this response.
I do know that I should not be using the fields of Outer before it has been properly created Not necessarily. You cannot use members before they are initialised, but you can use members that are already initialised to initialise other members. The catch is that the members are initialised in order of declaration, not in order they appear in initialiser list. inner is declared before outerString, so it's always initialised first. I feel that the real answer is likely that just because I do not have a compiler error does not mean that something is correct. That is correct, you have Undefined Behaviour, because you access a reference (outerString) before it's initialised. You compiler should warn you about that if you have warnings enabled (see it online with warnings). An interesting side note is that, if I remove either of the superfluous strings, I get a compiler error or it will simply segfault, and that is kind of what I had expected it to do. Undefined Behaviour is undefined, anything can happen. For me, program from one compiler prints nothing and exits normally, from a different compiler prints a lot of whitespace and then crashes. You can make it work by reordering your members (see it online): struct Outer { Outer(std::string &outerString, std::string &superfluousString, std::string &innerString): outerString(outerString), inner(*this) {} std::string &outerString; //declared before 'inner' struct Inner { Inner(Outer &outer) { std::cout << outer.outerString; } } inner; };
74,539,437
74,539,915
Is it possible to enumerate/scan available USB ports with Boost Asio C++ library
I want to use Boost Asio library to connect my USB device. It works. Now I want to enumerate/scan all possible USB devices to see which one can be used. Is that possible in Boost Asio library? I haven't found any function nor information about that. This is the most closed scenario to find USB ports. But not sure if it's a proper solution. #include <stdio.h> #include <boost/asio.hpp> int main() { boost::asio::io_service io; boost::asio::serial_port port(io); char portName[10]; for (int i = 0; i < 256; i++) { try { sprintf_s(portName, "COM%i", i); port.open(portName); if (port.is_open()) { printf("Port COM%i is a possible USB port\n", i); port.close(); } } catch (...) { printf("Port COM%i is not a possible USB port\n", i); } } return 0; }
That's not a feature of the library. Since you are looking for windows, consider using WMI interface to enumerate serial ports. E.g. in C# code: try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSSerial_PortName"); foreach (ManagementObject queryObj in searcher.Get()) { Console.WriteLine("InstanceName: {0}", queryObj["InstanceName"]); Console.WriteLine("PortName: {0}", queryObj["PortName"]); } } catch (ManagementException e) { MessageBox.Show("An error occurred while querying for WMI data: " + e.Message); }
74,539,774
74,540,289
How to optimize this code for speed and get rid of the nested loop?
I was trying to solve This problem, but I keep getting Time limit exceeded, when the input is 100000. I need to optimize the nested loop somehow. #include <iostream> using namespace std; int main(){ int arr[100000]; int n, x, q, m; cin >> n; //number of shops that sell the drink for (int i = 0; i < n; i++){ cin >> x; //prices of each drink in the shop arr[i] = x; //add it to the array } cin >> q; //number of days for (int i = 0; i < q; i++){ cin >> m; // money the person will be able to spend on each day int count = 0; for (int j = 0; j < n; j++){ if (m >= arr[j]){ //if the amount of money is more or equal // to the price of bottle, increase counter // (number of shop we can buy from) count++; } } cout << count << '\n'; //the number of shops the person can buy drinks in with his money } } I even tried another approach with sort and upper bound but still TLE #include <iostream> #include <algorithm> using namespace std; int main(){ int arr[200000]; int n, x, q, m; cin >> n; for (int i = 0; i < n; i++){ cin >> x; arr[i] = x; } cin >> q; for (int i = 0; i < q; i++){ cin >> m; int count = 0; //sort the array sort(arr, arr + n); //find the upper bound int upper1 = upper_bound(arr, arr + n, m) - arr; cout << upper1 << '\n'; } } link to my FIRST solution after submission here link to my SECOND solution after submission here
It actually appears that your second solution CAN be optimized, by sorting your arr only once, before going into a loop.
74,539,849
74,594,851
Unreal engine Abstract class example c++
i have been looking for quite some time online for a good Abstract class (UCLASS(Abstract)) example but haven't came accross a good one yet. Is there anyone with a good Link i can goto or Anyone who could show me a simple example, i would appreciate alot. WeaponBase.h UCLASS(Abstract, Blueprintable) class FPS_API AWeaponBase : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AWeaponBase(); /** This will be used in sub classes */ UFUNCTION(BlueprintCallable, Category = "Functions") virtual void OnFire(AFPSCharacter* Character); } Weapon_Assault.h UCLASS() class FPS_API AWeapon_Assault : public AWeaponBase { GENERATED_BODY() public: FVector spread; AWeapon_Assault(); }; Weapon_Assault.cpp #include "Weapon_Assault.h" AWeapon_Assault::AWeapon_Assault() { AWeaponBase(); spread = FVector(0.5f, 0.0f, 100.0f); } // this function from abstract super class void OnFire(AFPSCharacter* Character) { } The original code is quite big so i don't want to post it here, but this is basically what it looks like, and i keep getting errors. Also i can't even declare "OnFire" in main class and subclass at the same time?!
All class definitions must have ; after last } Like this: UCLASS(Abstract) class UAnimalBase : public UObject { GENERATED_BODY() public: UAnimalBase(const FObjectInitializer& ObjectInitializer); }; You need to add a declaration of an overridden function to your Weapon_Assault.h UCLASS() class FPS_API AWeapon_Assault : public AWeaponBase { GENERATED_BODY() public: FVector Spread; AWeapon_Assault(); virtual void OnFire(AFPSCharacter* Character) override; // THIS ONE }; Note that you don't need UFUNCTION() specifier above the overridden function, only on the first declaration. AWeapon_Assault::AWeapon_Assault() also has a mistake. You don't call constructors of parent classes in C++ they will be called automatically. AWeapon_Assault::AWeapon_Assault() { // AWeaponBase(); THIS LINE IS WRONG Spread = FVector(0.5f, 0.0f, 100.0f); } Create a definition for your functions in the abstract class (they can stay empty). Yes, it doesn't make sense though it does. Abstract is a specifier only inside of UnrealEngine but code still needs to be compiled with C++ standards. The absence of these definitions will cause compile errors. We use UpperCamelCase or PascalCase in Unreal Coding Standart which is nice to have. But that one is not necessary. So your variable should be FVector Spread; Also you probably shall wrap it with UPROPERTY() macro but that's a different topic.
74,540,529
74,540,549
Undefined reference when building AzerothCore module
I followed the steps on how to install azerothcore. I remembered I could add Modules, so I went in the website of azerothcore and downloaded a few modules. Before I downloaded them I checked and saw it says that it's building on master core, but for some reason I have the following error: /usr/bin/ld: ../../../modules/libmodules.a(ModulesLoader.cpp.o): in function `AddModulesScripts()': /root/azerothcore/build/modules/gen_scriptloader/static/ModulesLoader.cpp:60: undefined reference to `Addmod_1v1_arena_masterScripts()' /usr/bin/ld: /root/azerothcore/build/modules/gen_scriptloader/static/ModulesLoader.cpp:61: undefined reference to `Addmod_boss_announcer_masterScripts()' /usr/bin/ld: /root/azerothcore/build/modules/gen_scriptloader/static/ModulesLoader.cpp:63: undefined reference to `Addmod_npc_buffer_masterScripts()' /usr/bin/ld: /root/azerothcore/build/modules/gen_scriptloader/static/ModulesLoader.cpp:64: undefined reference to `Addmod_npc_spectator_masterScripts()' /usr/bin/ld: /root/azerothcore/build/modules/gen_scriptloader/static/ModulesLoader.cpp:65: undefined reference to `Addmod_reward_shop_masterScripts()' /usr/bin/ld: /root/azerothcore/build/modules/gen_scriptloader/static/ModulesLoader.cpp:66: undefined reference to `Addmod_solocraft_masterScripts()' clang: error: linker command failed with exit code 1 (use -v to see invocation) make[2]: *** [src/server/apps/CMakeFiles/worldserver.dir/build.make:175: src/server/apps/worldserver] Error 1 make[1]: *** [CMakeFiles/Makefile2:1086: src/server/apps/CMakeFiles/worldserver.dir/all] Error 2 make: *** [Makefile:130: all] Error 2 and I am not capable of fixing it. Can anyone please help?
Remove _master from all module subdirectories. You can avoid this error by using git clone or cloning the modules in general with a git interface, instead of downloading a .zip file.
74,540,793
74,540,870
How to create vector to store addresses of all children?
I am trying to create a basic game engine in C++ and I want an Engine object to be able to loop through all the GameObject children to run their update methods, to do this I want to use a vector of all children within the Engine class. For example: This is similar to what I have been trying to do: Parent Engine Class class Engine { public: Engine() {}; std::vector<GameObject> GameObjects; //Vector to store all GameObjects void AddNewObject(GameObject& obj) { GameObjects.push_back(obj); //Add new object to the vector array } void Run() { for (int i = 0; i < GameObjects.size(); i++) { GameObjects[i].Update(); //Run the update method of each GameObject } } } GameObject Child Class class GameObject : public Engine { public: GameObject() {} void Update() { //Do stuff } } Main code loop int main(void) { Engine engine; GameObject object; engine.AddNewObject(object); //Add object engine.run(); } Any help would be greatly appreciated, Thanks.
There are a few issues here. First, your vector needs to be a vector of references or pointers, otherwise GameObjects.push_back(obj); makes a copy of obj to place into the vector (unless you move it) and polymorphism won't work (you can't hold subclasses of GameObject). How you approach this depends on which object you want to own the memory associated with each GameObject. A trivial fix is is by using a vector of pointers: class Engine { public: Engine() {}; std::vector<GameObject*> GameObjects; //Vector to store all GameObjects void AddNewObject(GameObject& obj) { GameObjects.push_back(&obj); //Add new object to the vector array } void Run() { for (int i = 0; i < GameObjects.size(); i++) { GameObjects[i]->Update(); //Run the update method of each GameObject } } } However, with modern, C++ you would want to probably use a smart pointer like unique_ptr: class Engine { public: Engine() {}; std::vector<std::unique_ptr<GameObject>> GameObjects; //Vector to store all GameObjects void AddNewObject(std::unique_ptr<GameObject> obj) { GameObjects.push_back(std::move(obj)); //Add new object to the vector array } void Run() { for (int i = 0; i < GameObjects.size(); i++) { GameObjects[i]->Update(); //Run the update method of each GameObject } } } By using a unique pointer, you would have to change your other code: int main(void) { Engine engine; std::unique_ptr<GameObject> object = std::make_unique<GameObject>(); // Transfers memory ownership of `object` into `engine` engine.AddNewObject(std::move(object)); //Add object engine.run(); } Lastly, your class hierarchy looks invalid. You probably don't need or want GameObject to be a subclass of Engine since they don't share anything in common. GameObject may likely be a good base class itself and other game objects would inherit it.
74,541,494
74,541,566
std::swap of std::priority_queue with lambda comparator compiles under C++20 but not C++17: "error: object of type value_compare cannot be assigned"
The following code, which std::swaps two std::priority_queue<int, std::vector<int>, decltype(some lambda)>s, results in a compiler error in C++17, but not in C++20. #include <queue> int main() { auto cmp = [](int x, int y) {return x > y;}; std::priority_queue<int, std::vector<int>, decltype(cmp)> pq1(cmp), pq2(cmp); std::swap(pq1, pq2); // adding this line results in an error return 0; } The error under C++17 is error: object of type 'value_compare' (aka '(the lambda cmp)') cannot be assigned because its copy assignment operator is implicitly deleted {c = _VSTD::move(__q.c); comp = _VSTD::move(__q.comp); return *this;} note: in instantiation of member function 'std::priority_queue<int, std::vector<int>, (lambda at main.cpp:13:16)>::operator=' requested here __x = _VSTD::move(__y); note: in instantiation of function template specialization 'std::swap<std::priority_queue<int, std::vector<int>, (lambda at main.cpp:13:16)>>' requested here swap(pq1, pq2); I feel the key here is that somehow, the lambda cmp's copy assignment operator is implicitly deleted. I've learned from the top answer at std::priority_queue syntax with lambda is confusing that C++20 made lambdas without default captures default-constructible (see cppreference source as well), but the issue here seems to be with copy-constructing, not default-constructing. Why doesn't the code compile under C++17, and what changes in C++20 let it compile?
"seems to be with copy-constructing": No, as the error message says it is with copy-assigning. Swapping requires reassignment between the two objects, not only construction, because the two objects are not replaced by new ones. Only their values are exchanged. Before C++20 lambdas were not assignable at all and so this can't work. Since C++20 lambdas without capture are copy-assignable and so this works. If you want a quick-and-dirty workaround for C++17, you can convert a non-generic lambda without captures to a function pointer which is copy-assignable (and -constructible). The function pointer conversion can be done explicitly or implicitly with the + trick. Note that one can cause UB if using this incorrectly (see below) and that it is likely less performant, requiring an indirect function call to the comparator: auto cmp = +[](int x, int y) {return x > y;}; std::priority_queue<int, std::vector<int>, decltype(cmp)> pq1(cmp), pq2(cmp); std::swap(pq1, pq2); // works now The clean and performant solution that also works in the generic case is to use a proper function object type with a name: struct cmp { // might want to add noexcept/constexpr here bool operator()(int x, int y) const {return x > y;} }; std::priority_queue<int, std::vector<int>, cmp> pq1, pq2; std::swap(pq1, pq2); // works now Note that here you don't need to pass anything to the constructor. The function object type is default-constructible. Specifically for the lambda in your question, you can also just use std::greater<int> or std::greater<> as the type. std::greater implements a predicate function object for x > y, in the latter version with deduced parameter types. If you don't pass cmp in the function pointer variant to the constructor, the default-initialization will initialize it to a null pointer value and cause undefined behavior if actually used by the priority queue. In C++20 you also don't need to actually pass cmp in your original variant to the constructors, because lambdas without capture are now also default-constructible as you mentioned.
74,541,783
74,542,054
Singly linked list with unique_ptr
I am trying to use smart pointers (std::unique_ptr) to create a singly linked list. Here is an example of a singly linked list with raw pointer. struct Node { int data; Node *next = nullptr; Node(int data) : data{data}, next{nullptr} {} ~Node() { std::cout << "Destroy node with data: " << data << '\n'; } }; void print_list(Node *head) { while (head != nullptr) { cout << head->data << " --> "; head = head->next; } cout << "nullptr" << std::endl; } void insert(Node *&head, int data) { Node *new_node = new Node{data}; new_node->next = head; head = new_node; } int main(int argc, char *argv[]) { Node *head = nullptr; for (int i = 0; i < 5; ++i) { insert(head, i); } print_list(head); return 0; } The output is: 4 --> 3 --> 2 --> 1 --> 0 --> nullptr Apparently there is memory leak in the above code (destructor is not called). Now I want to use smart pointer to achieve the same thing: struct Node { int data = 0; std::unique_ptr<Node> next; Node(int data) : data{data}, next{nullptr} {} ~Node() { std::cout << "Destroy node with data: " << data << '\n'; } }; void print_list(std::unique_ptr<Node> head) { while (head != nullptr) { std::cout << head->data << " --> "; head = std::move(head->next); } std::cout << "nullptr" << std::endl; } void insert(std::unique_ptr<Node> &&head, int data) { std::unique_ptr<Node> new_node{std::make_unique<Node>(data)}; new_node->next = std::move(head); head = std::move(new_node); } // g++ -std=c++17 -Wall 2_1.cpp && ./a.out int main(int argc, char *argv[]) { std::unique_ptr<Node> head{nullptr}; for (int i = 0; i < 5; ++i) { insert(std::move(head), i); } print_list(std::move(head)); return 0; } The output is: 4 --> Destroy node with data: 4 3 --> Destroy node with data: 3 2 --> Destroy node with data: 2 1 --> Destroy node with data: 1 0 --> Destroy node with data: 0 nullptr We can observe that the life time of new_node ends when insert() returns. I would like to know if it's possible to use smart pointers to achieve singly linked list and retains the functions interface as above.
First thing, there is a problem with your print_list implementation(for both version for unique_ptr only). With your print_list, every time you assign head with a different uniq_ptr, you are actually deallocating the only Node in head, which is not desired. Instead, in your print_list, you should first create a temporary pointer pointing to head, then only iterate on the temporary pointer. Now onto your unique_ptr version, you don't have to pass a unique_ptr as rvalue reference, you can also pass it as lvalue reference. Instead, your function signature would probably look like: void print_list(const std::unique_ptr<Node>& head); void insert(std::unique_ptr<Node> &head, int data); This allow you to call them without using std::move in your main. Now on to definitions. For your insertion, what you have is you first create a new Node with the given value, then you assign the old head to new node's next, and make the new node as the new head: void insert(std::unique_ptr<Node> &head, int data) { // Use `auto` to avoid typing `....<Node>` twice auto new_node = std::make_unique<Node>(data); new_node->next = std::move(head); head = std::move(new_node); } Alternatively, you can also add one more parameter to Node's constructor: Node(int data, std::unique_ptr<Node>&& next = nullptr) : data{data}, next{std::move(next)} {} Now you can simply create new_node like: void insert(std::unique_ptr<Node> &head, int data) { // No need to assign `Node::next` separately auto new_node = std::make_unique<Node>(data, std::move(head)); head = std::move(new_node); } Or even assign the new node to head directly: void insert(std::unique_ptr<Node> &head, int data) { head = std::make_unique<Node>(data, std::move(head)); } For print_list, we should first create a temporary pointer that points to the underlying object of head, then iterate the list by assigning the temporary pointer to its next object's underlying object: void print_list(const std::unique_ptr<Node>& head) { // Create a pointing to the underlying object // You can use `.get()` to get the underlying pointer auto current = head.get(); // No need to explicit compare pointer types to `nullptr` while (current) { std::cout << current->data << " --> "; // Make `current` point to the next underlying object current = current->next.get(); } std::cout << "nullptr" << std::endl; } Now your main would look like: int main(int, char *[]) { std::unique_ptr<Node> head; for (int i = 0; i < 5; ++i) { insert(head, i); } print_list(head); return 0; } Demo
74,542,479
74,542,782
i made c++ code where its need to pass structure pointer in a function
i got confused about the structure when i need to to pass the value in a function #include <iostream> using namespace std; struct student { int studentID; char studentName[30]; char nickname[10]; }; void read_student(struct student *); void display_student(struct student *); int main() { student *s; //struct student *ps; read_student(s); display_student(s); } void read_student(struct student *ps) { int i; for (i = 0; i <= 2; i++) { cout << "Enter the studentID : "; cin >> ps->studentID; cout << "Enter the full name :"; cin.ignore(); cin >> ps->studentName; cout << "Enter the nickname : "; cin.ignore(); cin >> ps->nickname; cout << endl; } } void display_student(struct student *ps) { int i; cout << "student details :" << endl; for (i = 0; i <= 2; i++) { cout << "student name : " << *ps ->studentName << " (" << &ps ->studentID << ")" << endl; ps++; } } its only problem at the variable at line 19 and when i try to edit it will became more problem student *s; //struct student *ps; //struct student *ps; read_student(s); display_student(s); also can someone explain how to transfer pointer value of structure to the function and return it back to the main function
You are suffering from some leftovers from your C-Language time. And, you have still not understood, how pointer work. A pointer (as its name says) points to something. In your main, you define a student pointer. But it is not initialized. It points to somewhere. If you read data from somewhere, then it is undefined behavior. For writing, it is the same, plus that the system will most likely crash. So, define a student. And if you want to give it to a sub-function, take its address with th &-operator (this address will point to the student) and then it will work. You need also to learn abaout dereferencing. Your output statement is wrong. Last but not least, if you want to store 3 students, then you need an array or some other storage where to put them . . . In your read function you always overwrite the previously read student and in your display function you show undetermined data. Please have a look at your minimal corrected code: #include <iostream> using namespace std; struct student { int studentID; char studentName[30]; char nickname[10]; }; void read_student( student*); void display_student( student*); int main() { student s; //struct student *ps; read_student(&s); display_student(&s); } void read_student( student* ps) { cout << "Enter the studentID : "; cin >> ps->studentID; cout << "Enter the full name :"; cin.ignore(); cin >> ps->studentName; cout << "Enter the nickname : "; cin.ignore(); cin >> ps->nickname; cout << endl; } void display_student( student* ps) { cout << "student details :" << endl; cout << "student name : " << ps->studentName << " (" << ps->studentID << ")" << endl; ps++; } And, the commenters are right. You must read a book.
74,542,563
74,542,644
How to write a multicharacter literal to a file in C++?
I have a structure defined array of objects with different data types, I'm trying to write the contents to a file but one of the char values is more than one character, and it's only writing the last character in the multicharacter literal to the file. The value in the char is 'A-', but only - is getting written. Is it possible to write the entirety of it? Before anybody suggests just using a string, I am required to use the char data type for Grade. The code I have looks like this: //Assignment12Program1 #include <iostream> #include <iomanip> #include <fstream> using namespace std; //Structure with student info struct studentInfo { char Name[100]; int Age; double GPA; char Grade; }; //Main function int main() { //Sets number of students in manually made array const int NUM_STUDENTS = 4; //Array with students created by me studentInfo students[NUM_STUDENTS] = { {"Jake", 23, 3.45, 'A-'}, {"Erica", 22, 3.14, 'B'}, {"Clay", 21, 2.80, 'C'}, {"Andrew", 18, 4.00, 'A'} }; //defines datafile object fstream dataFile; //Opens file for writing dataFile.open("studentsOutput.txt", ios::out); //Loop to write each student in the array to the file for (int i = 0; i < 4; i++) { dataFile << students[i].Age << " " << setprecision(3) << fixed << students[i].GPA << " " << students[i].Grade << " " << students[i].Name << "\n"; } dataFile.close(); return 0; } And the text file ends up displaying this: 23 3.450 - Jake 22 3.140 B Erica 21 2.800 C Clay 18 4.000 A Andrew
It is not possible to fit two characters in a single byte char. The simplest solution is to modify the data structure: struct studentInfo { . . char Grade[3]; // +1 for a null-terminator }; Then, you have to place A- in double-quotes like this: studentInfo students[NUM_STUDENTS] = { { "Jake", 23, 3.45, "A-" }, { "Erica", 22, 3.14, 'B' }, { "Clay", 21, 2.80, 'C' }, { "Andrew", 18, 4.00, 'A' } };
74,543,012
74,543,868
C++, std::remove_if with std::string. Resize string by popping it's end in lambda
Since std::remove() does not resize std::string, I've came up with an idea how to solve this: std::string s{"aabcdef"}; std::remove_if(s.begin(), s.end(), [&s](char a) { if (a == 'a') { s.pop_back(); return true; } return false; }); Excepted output: bcdef Actual output: bcd For some reason, it erases 4 characters instead of expected 2. If I try to pass an int instead and count true calls in lambda, it works as expected: int removes{}; std::remove_if(s.begin(), s.end(), [&removes](char a) { if (a == 'a') { ++removes; return true; } return false; }); for (int i{}; i < removes; ++i) s.pop_back(); //s = "bcdef"
Note the function/lambda you passed to std::remove_if isn't about what happened to the character you want to remove. It is about how to determine which character need to be removed. What that means is whatever happens within the lambda will happen before std::remove_if starting its removal algorithm. In your case, since you called pop_back() within the lambda, you are actually removing the last letter before remove_if can identify which character need to be removed. Another thing to note is, if std::remove doesn't actually remove, and your usage should only call pop_back() twice, how come you end up with 3 characters, instead of 5? The reason is because when you call the function remove_if(begin_it, end_it, some_predicate), some_predicate will be invoked by every element between begin_it and end_it, regardless of what happens within some_predicate. Note that both iterators are determined before any calls of the predicate, so even when you did pop_back() within the predicate, remove_if will continue running the predicate after the last character. In your case, since you have popped 2 characters, remove_if will actually run predicate on and shift both the null character and the character after the null character. In fact, if you run s.size(), you will notice the size is still 5 not 3. To properly remove the characters, you should either use the erase-remove idiom: s.erase(std::remove_if(s.begin(), s.end(), [](char c){ return c == 'a'; })); // or s.erase(std::remove(s.begin(), s.end(), 'a'); Or for C++20 or later, you can use: std::erase_if(s, [](char c){ return c == 'a'; }); // or std::erase(s, 'a');
74,543,174
74,543,320
How to recive second command while last command not completed?
How to recive second command while last command not completed? I have a application that receive command from message queue and process parser command to do something. But if last command is "start" and it need some time to completed, like 1 minute in the while loop. In the same time, another command "stop" incoming, how to implement? by thread? main() { while(true) { rc = mq_receive(rmqID, rbuff) if (rc < 0) { cout <<"receive timeout !!"<< endl; } else { cout <<"receive message : "<< rbuff << endl; std::string cmd = rbuff; if (cmd == "start") { cout <<"[receive message] flash_cmd = true"<< endl; flash_cmd = true; } else if (cmd == "stop") { cout <<"[receive message] stop command = true"<< endl; stop_cmd = true; } else { cout <<"[receive message] Command error!"<< endl; } } if (stop_cmd == true) { cout <<"stop process ......."<< endl; stop_flag = true; } if (flash_cmd == true) { cout <<"[programming] Start install Processing"<< endl; while { // do flash.... if(stop_flag == true) { break; } } } }
If you want to do two things at the same time, such as executing one message and simultaneously checking if you have received another, then the easiest solution would probably be starting a thread. However, be aware that you cannot poke a thread and tell it to just stop. If you want to be able to stop your "execute command" thread early, then you have to structure it something like (pseudo code): void threadFunc(std::atomic_bool stop) { do_first_part(); if(stop) return; do_second_part(); if(stop) return; ... The point is that you have to explicitly look for the stop condition yourself, and have the thread self-terminate if it is required to stop. Depending on what it is doing that takes time, you may also be able to use std::condition_variable to signal your thread.
74,544,973
74,546,521
How to change QGraphicsLineItem programmatically
I'm working on resizeable and moveable overlay items, at the moment on a cross-hair. To make it resizeable I need to change parameters of my two QGraphicsLineItems, my cross-hair consists of. But calling the functions like setLength(), setP1(), setP2() or setLine() of the two lines do not show any effect. Please consider the following code: mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QGraphicsRectItem> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private: Ui::MainWindow *ui; QGraphicsRectItem *_item; }; #endif // MAINWINDOW_H mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); QGraphicsScene *scene = new QGraphicsScene(this); _item = new QGraphicsRectItem(QRectF(0, 0, 100, 100)); _item->setFlag(QGraphicsItem::ItemIsMovable); _item->setPen(QColor(102, 102, 102)); auto l1 = new QGraphicsLineItem(0, 50, 100, 50, _item); auto l2 = new QGraphicsLineItem(50, 0, 50, 100, _item); l1->setPen(QColor(10, 255, 10)); l2->setPen(QColor(10, 255, 10)); scene->addItem(_item); ui->graphicsView->setScene(scene); ui->graphicsView->setAlignment(Qt::AlignTop | Qt::AlignLeft); ui->graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse); // make lines longer by 10 on button press connect(ui->resize, &QPushButton::clicked, this, [this]() { auto childs = _item->childItems(); if (childs.size() > 0) { auto line1 = dynamic_cast<QGraphicsLineItem *>(childs.at(0)); auto line2 = dynamic_cast<QGraphicsLineItem *>(childs.at(1)); line1->line().setLine(0, 55, 110, 55); //no effect line2->line().setLine(55, 0, 55, 110); //no effect } }); } MainWindow::~MainWindow() { delete ui; } Because I need to handle mousePressEvent, mouseMoveEvent also, I stopped to go with QGraphicsItemGroup. Thank you in advance.
Use QGraphicsLineItem::setLine instead: //... line1->setLine(0, 55, 110, 55); line2->setLine(55, 0, 55, 110);
74,545,075
74,549,840
How do I represent a 24-hour clock with the STL?
I'm looking for a solution from the STL, for dealing with "time of day". I am working on a simple unit test exercise, with behavior depending on whether current time is in the morning, evening or night. For a first iteration I used a humble integer as a stand-in for some "time object": using TimeOfDay = int; constexpr bool isBetween(TimeOfDay in, TimeOfDay min, TimeOfDay max) noexcept { return in >= min && in <= max; } constexpr bool isMorning(TimeOfDay in) noexcept { return isBetween(in, 6, 12); } constexpr bool isEvening(TimeOfDay in) noexcept { return isBetween(in, 18, 22); } constexpr bool isNight(TimeOfDay in) noexcept { return isBetween(in, 22, 24) || isBetween(in, 0, 6); } constexpr string_view getGreetingFor(TimeOfDay time) noexcept { if (isMorning(time)) { return "Good morning "sv; } if (isEvening(time)) { return "Good evening "sv; } if (isNight(time)) { return "Good night "sv; } return "Hello "sv; } This works but has a couple of smells: the int simply isn't the right type to represent a 24 hour clock isNight() requires an unnecessarily complicated comparison, due to wrapping (22-06) ideally I would like to be able actually use the system clock for some of my tests. std::chrono::system_clock::now() returns a std::chrono::time_point, so my ideal type should probably be something that can be compared to a time_point, or easily constructed from a time_point. Any pointers would be very appreciated! (I am working in Visual Studio with C++Latest (preview of the C++ working draft, so roughly C++23))
I'm going to start with the assumption that you're looking for the local time of day. chrono::system_clock represents UTC. So I recommend a helper function that takes std::chrono::system_clock::time_point and returns a std::chrono::system_clock::duration which represents the time elapsed since the most recent local midnight: using TimeOfDay = std::chrono::system_clock::duration; TimeOfDay get_local_time_of_day(std::chrono::system_clock::time_point tp) noexcept { using namespace std::chrono; auto time = current_zone()->to_local(tp); return time - floor<days>(time); } chrono::current_zone() returns a pointer to the chrono::time_zone that your computer is currently set to. This is used to convert the system_clock::time_point to a local time_point. This local time_point is a chrono::time_point but with a different clock that means "local time". The expression floor<days>(time) truncates the time_point to precision days, which effectively gives you a pointer to the most recently passed local midnight. Subtracting that from time gives you a chrono::duration since the local midnight. This duration will have the same precision as tp. This function can not be made constexpr because the rules for transforming UTC to local time is in the hands of your politicians and is subject to change (in many countries twice a year!). Now you can write isMorning (et al) like this: bool isMorning(std::chrono::system_clock::time_point in) noexcept { using namespace std::literals; return isBetween(get_local_time_of_day(in), 6h, 12h); } And call it like this: if (isMorning(system_clock::now())) ... Your logic for isNight looks fine to me. And your code for isBetween can stay like it is (picking up the new definition of TimeOfDay).
74,545,491
74,545,705
I am here to ask on how can I store the calculation history of my calculator in c++
I am new to the coding community and I am here to ask on how can I store the calculations that have been done in my calculator. I am currently new in this space and I am currently looking for answers T-T. my code goes like this thank you everyone! T-T pls be gentle on me. #include<iostream> #include<stdlib.h> using namespace std; int calculator(); void history(); void choice(); int main() { int x; cout << "\t\t\t\tWhat do you want to do?\n\n"; cout << "\t\t\t\t[1] Standard calculator\n"; cout << "\t\t\t\t[2] History\n"; cout << "\t\t\t\t[3] Exit\n\n\n\n"; cout << "\t\t\t\tChoice: "; cin >> x; switch (x) { case 1: calculator(); break; case 2: history(); break; case 3: cout << "\n\n\nThank you for using my calculator!"; exit(4); break; default: cout << "Enter a correct choice"; main(); } } int calculator() { double x, y; float sum = 0.0, dif = 0.0, prod = 1.0, quo = 1.0; int i; char op, back; do { system("CLS"); cout << "\t\t#CALCULATOR#" << endl; cout << endl << endl; cout << "Calculate 2 numbers: (example 1 + 1 or 2 * 2)\n"; cin >> x >> op >> y; switch (op) { case '+': sum = x + y; cout << "The sum of " << x << " and " << y << " is " << sum; break; case '-': dif = x - y; cout << "The difference of " << x << " and " << y << " is " << dif; break; case '*': prod = x * y; cout << "The product of " << x << " and " << y << " is " << prod; break; case '/': if (y == 0) cout << "Undefined"; else quo = x / y; cout << "The quotient of " << x << " and " << y << " is " << quo; break; default: cout << "Invalid operator"; break; } cout << "\nContinue[Y/N]: "; cin >> back; cout << endl << endl; if (back != 'Y' && back != 'y' && back != 'N' && back != 'n') { cout << "Please enter a correct choice" << endl; choice(); } else if (back == 'N' || back == 'n') { system("pause"); system("CLS"); main(); } } while (back == 'y' || back == 'Y'); cout << "Thank you"; system("pause"); system("CLS"); } void choice() { char c; do { cout << "Do you want to continue? [Y/y or N/n]" << endl; cin >> c; if (c == 'Y' || c == 'y') calculator(); else if (c == 'N' || c == 'n') { system("pause"); system("cls"); main(); } else cout << "Please enter a correct choice\n"; choice(); } while (c != 'y' || c != 'Y' || c != 'N' || c != 'n'); cout << "Enter a correct choice"; } void history() { cout << "I still dont know how T - T"; } I wanted to store the past calculations using arrays but i dont know how to actually put it in my code T-T pls help
You want to #include <vector> and make a history std::vector, that holds strings: std::vector<std::string> history; When you do the calculcation, don't output to cout, but to a std::ostringstream first (located in <sstream>): std::ostringstream caclulation_stream; switch (op) { case '+': sum = x + y; caclulation_stream << "The sum of " << x << " and " << y << " is " << sum; break; case '-': dif = x - y; caclulation_stream << "The difference of " << x << " and " << y << " is " << dif; break; case '*': prod = x * y; caclulation_stream << "The product of " << x << " and " << y << " is " << prod; break; case '/': if (y == 0) caclulation_stream << "Undefined"; else quo = x / y; caclulation_stream << "The quotient of " << x << " and " << y << " is " << quo; break; default: caclulation_stream << "Invalid operator"; break; } this way, you can save the string to history. push_back() adds the string to the vector. Don't forget to also print out the string, so it's still displayed in the console. auto calculation_string = caclulation_stream.str(); history.push_back(calculation_string); std::cout << calculation_string; to display the history, you can loop over the vector and print out the elements: void show_history() { for (const auto& entry : history) { std::cout << entry << '\n'; } } this should give you the basic ideas on how to implement this. Read here why you shouldn't be using namespace std;.
74,545,953
74,546,040
My VS 2022 doesn't handle over than 32 bit bitset
I am trying to convert 45 bit binary number into a hex number but when compiling, I get overflow error, but when applying the code on online C++ compiler, it works. My platform is X64. Any help please. int main() { stringstream ss; string binary_str("111000000100010010100000110101001000100011000"); bitset<45> n(binary_str); string f; ss << hex << n.to_ulong() << endl; // error happens here f = ss.str(); cout << f; return 0; } When compile this code above on online C++ compiler I get a correct result which is OX1c08941a9118.
unsigned long is 32bit with MSVC. Also when compiling for x64. You need unsigned long long to get a 64bit integer, so in this case you can use to_ullong: ss << hex << n.to_ullong() << endl;
74,546,017
74,546,575
using enum as semantic type in Bison C++
How can I use an enum as type as shown below %type <order_direction> ordering_direction opt_ordering_direction when i have defined order_direction in a separate header file as enum enum_order : int { ORDER_NOT_RELEVANT = 1, ORDER_ASC, ORDER_DESC }; enum_order order_direction; which i include in the Bison file? When i try to link the object files i get this error: error: ‘order_direction’ is not a type 5091 | basic_symbol (typename Base::kind_type t, order_direction&& v, location_type&& l) I also use the following definitions in my .y file %define api.token.constructor %define api.value.type variant %define parse.assert
The problem is that enum_direction is an enumerator and not an enumaration type. This means enum_direction cannot be used as a type. To solve this, you must use a type where a type is required. This means you can use enum_order as the type of the function parameter instead of enum_direction( as the former is a type).
74,546,189
74,546,766
std::transform applied to data member of sequence's element
Please help me to find a more elegant way to rewrite this snippet using std::transform or similar algorithm: for (auto& warning : warnings) { NormalizePath(warning.path, GetParsedPathLength(warning.path), longestPathLength); }; Where warning is a struct. This is what I came up with: std::transform(begin(warnings), end(warnings), begin(warnings), [longestPathLength](auto& warning) { NormalizePath(warning.path, GetParsedPathLength(warning.path), longestPathLength); return warning; }); But it requires a copy of full data-structure. Is there a way to create a modifiable view of a original sequence that contains only path member? So transform could be rewritten only accepting and returning modified path. And in the end all the changes should affect original warnings sequence.
With ranges (C++20), you might "shorter" first version to: for (auto& path : warnings | std::views::transform(&Warning::path)) { NormalizePath(path, GetParsedPathLength(path), longestPathLength); }
74,546,904
74,548,211
Somewhat inconsistent need for template disambiguator
In the example below, I need to use the template disambiguator in the line marked as #1, while it appears to be unnecessary in the other occurrence of a similar pattern. What does it make the difference? #include <cstdint> #include <utility> #include <array> #include <vector> #include <ranges> template<std::size_t n, typename TFn> constexpr void constexpr_for(TFn Fn) { [&Fn]<std::size_t... i>(std::index_sequence<i...>) { (Fn(std::integral_constant<std::size_t, i>{}), ...); } (std::make_index_sequence<n>{}); } struct TVertex {}; class TFace { public: static constexpr std::size_t NVertex = 3u; private: std::array<TVertex const *, NVertex> VertexVec; public: template<std::size_t i> TVertex const &GetVertex() const { return *std::get<i>(VertexVec); } }; void f(std::vector<TFace> const &FaceVec) { for (auto const &[i, Face1] : std::views::zip(std::views::iota(0u), FaceVec)) constexpr_for<TFace::NVertex>([&](auto const j) { for (auto const &[_, Face2] : std::views::zip(std::views::iota(0u), FaceVec) | std::views::drop(i + 1u)) constexpr_for<TFace::NVertex>([&](auto const k) { TVertex const &Vertex1 = Face1.GetVertex<j>(); TVertex const &Vertex2 = Face2.template GetVertex<k>(); // #1 }); }); } I’m using GCC trunk. Here’s a Compiler Explorer link: https://godbolt.org/z/Kh6n6G4hW
Here's a minimal way to reproduce your error: #include <utility> class TFace { public: template<int i> void GetVertex() const {} }; template<typename> void f1() { auto const &[_, Face2] = std::pair<int, TFace>{}; Face2.GetVertex<0>(); // #1 } Since this compiles on clang, I'm thinking that this is a GCC bug. GCC seems to think that Face2 is a dependent name, even though it clearly isn't (The types of all the variables in: std::views::zip(std::views::iota(0u), FaceVec) | std::views::drop(i + 1u) are not dependent on any template argument). This bug does have a simple workaround fortunately, adding Face2.template GetVertex as you have. It might look better or be less confusing if you wrote Face1.template GetVertex as well. My hypothesis is that in the structured binding, Face2 is initialized similarly to get<1>(*zip_iterator) with ADL, and GCC incorrectly assumes that this is dependent (even though zip_iterator is not dependent). The reason Face1 works without .template is that it is defined in f which is not a template, so it cannot possibly be dependent. Face2 is templated, since it is in a generic lambda, even if it doesn't end up being dependent.
74,546,962
74,547,037
How to pass generic arguments to the nested generic classes in C++
I have a class and a nested class in C++ and they are both generic classes. #define GENERIC template<typename T> GENERIC class Class1 final{ private: GENERIC class Class2 final{ private: T class2Field{}; }; T class1Field{}; }; I want to pass the type parameter T that is passed to Class1 when instantiating it, all the way to the Class 2. How can I achieve that?
Class2 can see the declaration of Class1, therefore will use Class1's T when not declared a templated class: template<typename T> class Class1 final { private: class Class2 final { private: T class2Field{}; }; T class1Field{}; }; so Class1<int>::Class2::class2Field will be of type int. If you want Class2 still to be a templated class, see this answer. better not use macros: Why are preprocessor macros evil and what are the alternatives?.
74,547,165
74,548,361
how to create derive class from base class
I have base class like this: class Base{ public: virtual Base *createNew(){ auto newItem = new Base(); setNew(newItem); return newItem; }; void setNew(Base *item){ item->value = value; }; private: int value; }; A number of derived classes are shown below, each of which has a createNew interface that returns a derived object. class Derive1 : public Base{ Derive1 *createNew(){ auto newItem = new Derive1(); setNew(newItem); return newItem; }; void setNew(Derive1 *item){ Base::setNew(item); item->value1 = value1; }; private: int value1; }; class Derive2 : public Base{ Derive2 *createNew(){ auto newItem = new Derive2(); setNew(newItem); return newItem; }; void setNew(Derive2 *item){ Base::setNew(item); item->value2 = value2; }; private: int value2; }; class Derive3 : public Base{ Derive3 *createNew(){ auto newItem = new Derive3(); setNew(newItem); return newItem; }; void setNew(Derive3 *item){ Base::setNew(item); item->value3 = value3; }; private: int value3; }; int main(int argc, char *argv[]) { std::list<Base *> list; list.push_back(new Derive1); list.push_back(new Derive2); list.push_back(new Derive3); list.push_back(new Derive2); list.push_back(new Derive1); std::list<Base *> listNew; for(auto item : list) { listNew.push_back(item->createNew()); } ... //ignore the memory leak. } Is there any easy way to not write every createNew in the derived class, because they are similar, the only difference is the type. Do templates help?
Supposedly you want to use the Curiously Recurring Template Pattern (CRTP) for this. Here is an example where we introduce template class BaseT that inherits from Base. Note how each derived class inherits from BaseT passing itself as template parameter. class Base { public: virtual Base* createNew() = 0; virtual ~Base() {} }; template <typename T> class BaseT : public Base { public: Base* createNew() override { return createDerived(); } T* createDerived() { auto newItem = new T(); setNew(newItem); return newItem; }; void setNew(T* item){ item->value = value; setNewDerived(item); }; virtual void setNewDerived(T* item) {} virtual ~BaseT() {} private: int value; }; class Derive1 : public BaseT<Derive1> { public: void setNewDerived(Derive1* item) override { item->value1 = value1; } private: int value1; }; class Derive2 : public BaseT<Derive2> { public: void setNewDerived(Derive2 *item) override { item->value2 = value2; } private: int value2; }; class Derive3 : public BaseT<Derive3> { public: void setNewDerived(Derive3 *item) override { item->value3 = value3; }; private: int value3; }; Is this what you are trying to do?
74,547,236
74,549,572
How to reassign a time_point from clock::now()?
Given a std::chrono::sys_seconds time, one might expect to reassign time from its clock with something like: time = decltype(time)::clock::now(); However, this would likely fail, because decltype(time)::clock::duration has nothing to do with decltype(time). Instead it is a predefined unit(likely finer than seconds), so you would have to manually cast it to a coarser unit. Which means you would need to write something like: time = std::chrono::time_point_cast<decltype(time)::duration>(decltype(time)::clock::now()); So my question is if there is a shorter syntax to do this?
an obvious solution is just write your own function template<typename Clock, typename Duration> void SetNow(std::chrono::time_point<Clock,Duration>& time){ time = std::chrono::time_point_cast<Duration>(Clock::now()); } // use void foo(){ auto time = std::chrono::system_clock::now(); SetNow(time); } you can also do some fancy overload struct Now_t{ template<typename Clock,typename Duration> operator std::chrono::time_point<Clock,Duration>()const{ return std::chrono::time_point_cast<Duration>(Clock::now()); } consteval Now_t operator()()const{return {};} // enable time = Now(); } Now; // use void foo() { auto time = std::chrono::system_clock::now(); time = Now; time = Now(); }
74,547,781
74,547,904
C++ Is there a performance difference when assigning a new value to a variable vs assigning them via methods
I've been mostly using private variables when writing a class and using methods to set the variable's value. Especially when it comes array, indexing them would be just using the operator[]. But what if I were to put them inside a method like getIndex(int x), and calling that method. Would that have any impact to the performance like slowing it down a little bit?
That really depends on whether the compiler can inline the calls to these getters/setters. It can inline them if either: Each translation unit has access to their definitions - in practice if they are in the header file of the class. Either inlined into the class definition or inline-defined after it. You enable link-time optimizations. Any decent compiler with optimizations enabled will inline simple getters/setters if possible and in that case the assembly will be exactly the same. But should you care? No. Write clean code first. Unless you can prove with a benchmark there are performance issues stemming from this. And in that case, enable LTO or put the definitions in the headers. On the other hand, having the members private and the access hidden behind methods is very good abstraction. If you ever decide to e.g. implement bounds checking, good luck refactoring all those object.array[idx] expressions across the code base.
74,547,838
74,576,185
C++ Linked list problem. i want to know why my output is correct. i think i didn't connect first node yet
here is my code. list of problems 1.if i write "std::cout << this->first->new_data << std::endl;" in function void printout it will get an error you can look in my code i comment it already BUT in while loop it can show output and it correct WHY??? 2.I haven't connected to the first node yet but the output is correct.WHY?? please help. #include <iostream> class Node { //this class create node public: int new_data = 0; //set default value Node* next = nullptr; }; class linked_list { //Create linked list public: Node *first; //represent the first node of linked list; Node *last; //represent the last node of linked list; linked_list() {// constructor assign default this value to NULL; this->first = NULL; this->last = new Node(); } void pushback(int add_data); //create abstract class for write out side class; void printout() { //show the values of linked list; while (this->first != NULL) { std::cout << this->first->new_data << std::endl; this->first = this->first->next; } //std::cout << this->first->new_data << std::endl;<- this error/*Exception thrown: read access violation.this->first was nullptr.*/ //std::cout << this->last->data << std::endl;<- this work } }; void linked_list::pushback(int new_data) {//push from back function if (this->first == NULL) { // if 1st node is NULL do this Node* new_node = new Node(); /*create new_node assign value and connected to linked list*/ new_node->new_data = new_data; new_node->next = NULL; this->first = new_node; this->last = new_node; } else { Node* new_node = new Node(); /*create new_node assign value and connected to linked list*/ new_node->new_data = new_data; new_node->next = this->last; this->last->next = new_node; this->last = new_node; this->last->next = NULL; } } int main() { linked_list a; a.pushback(3); a.pushback(9); a.pushback(6); a.pushback(66); a.pushback(77); a.pushback(99); a.pushback(10000); a.pushback(10001); a.printout(); } I want someone explain it to me and i will be glad if you wrote an example code about how I can fix it.
Ok now i have solved the problem. Thank you for your comments and advice. I have studied about pointer and I quite understand. here is my code that i fixed. It might not be good but i think it is the best for me now. #include <iostream> class Node { //this class create node public: int new_data; //set default value Node* next = nullptr; }; class linked_list { //Create linked list public: Node* first; //represent the first node of linked list; Node* last; //represent the last node of linked list; linked_list() {// constructor assign default this value to NULL; this->first = nullptr; //this->last = new Node();->DO NOT DO THIS BECAUSE IT WILL CREATE MEMORY LEAK ["new" keyword it allocate memory]. } void pushback(int add_data); //create abstract class for write out side class; void insertfromfront(int add_data); void printout() { //show the values of linked list; while (this->first != nullptr) { std::cout << this->first->new_data << std::endl; this->first = this->first->next; } } }; void linked_list::pushback(int new_data) {//push from back function if (this->first == nullptr) { // if 1st node is NULL do this Node* new_node = new Node(); /*create new_node assign value and connected to linked list*/ new_node->new_data = new_data; new_node->next = nullptr; this->first = new_node; this->last = new_node;//this is for connect the node. /*std::cout << "an adress of value of new_node " << &new_node << std::endl; std::cout << "an dress of new_node " << new_node << std::endl; std::cout << "adress values of first " << this->first << std::endl; std::cout << "address value of last " << this->last << std::endl; std::cout << "address first " << &this->first << std::endl; std::cout << "address last " << &this->last << std::endl;*/ } else { Node* new_node = new Node(); /*create new_node assign value and connected to linked list*/ new_node->new_data = new_data; new_node->next = nullptr; this->last->next = new_node;//this is for connect the node this->last = new_node;//this put tail to the last of linked list. } } int main() { linked_list a; std::cout << "Adress of a " << &a << std::endl; /*a.pushback(3); a.pushback(9); a.pushback(6); a.pushback(66); a.pushback(77); a.pushback(99); a.pushback(10000); a.pushback(10001);*/ a.printout(); }
74,547,903
74,552,472
Algorithm too slow on large scale input case, and dynamic programming optimization
Problems I found My code works on short input but not on long input (test cases 1, and 2 work, but 3 takes too much time) I believe code can be optimized (by dynamic programming), but how? Guess recursion limit problem(call stack limit) can occur in large scale input Preconditions the array is sorted in ascending order starts with currentNumber = 0, k = 1 k = the difference to the previous number nextNumber = currentNumber + k - 3 or nextNumber = currentNumber + k or nextNumber = currentNumber + k + 1 or nextNumber = currentNumber + k + 2 if nextNumber is not in the array, it is the end of the path nextNumber always has to be greater than currentNumber find the biggest number that can reach 2 <= len(arr) <= 2000 0 <= arr[i] <= 10^5 arr[0] = 0, arr[1] = 1 space limit: 1024MB time limit: 1sec Examples test case1 input 7 0 1 2 3 8 9 11 test case1 output 3 test case2 input 8 0 1 3 5 6 8 12 17 test case2 output 17 test case3 input 80 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 31 32 33 35 37 39 40 41 43 44 45 48 49 50 53 54 57 58 61 63 67 68 73 74 79 80 83 85 90 91 94 96 101 103 109 111 120 122 130 131 132 155 160 165 170 175 176 177 190 200 250 test case3 output(expected) 175 Code #include <iostream> using namespace std; int largestNumber = 0; // search for a index at a given number // search only bigger than given index // given array is sorted // return 0 if not found int findIndex(int *numbers, int size, int target, int index) { for (int i = index + 1; i < size; i++) { if (numbers[i] == target) { return i; } } return 0; } void findLargestNumberCanReach(int *numbers, int size, int k, int currentNumber, int currentIndex) { if (currentIndex == size - 1) // reached to the end of the array { largestNumber = currentNumber; return; } else if (currentIndex == 0) // can't find next number { if (currentNumber - k > largestNumber) // last currentNumber is biggest { largestNumber = currentNumber - k; } return; } currentIndex = findIndex(numbers, size, currentNumber + (k - 3), currentIndex); findLargestNumberCanReach(numbers, size, k - 3, currentNumber + (k - 3), currentIndex); currentIndex = findIndex(numbers, size, currentNumber + (k), currentIndex); findLargestNumberCanReach(numbers, size, k, currentNumber + (k), currentIndex); currentIndex = findIndex(numbers, size, currentNumber + (k + 1), currentIndex); findLargestNumberCanReach(numbers, size, k + 1, currentNumber + (k + 1), currentIndex); currentIndex = findIndex(numbers, size, currentNumber + (k + 2), currentIndex); findLargestNumberCanReach(numbers, size, k + 2, currentNumber + (k + 2), currentIndex); return; } int main() { int size; cin >> size; int *input = new int[size]; for (int idx = 0; idx < size; idx++) { cin >> input[idx]; } findLargestNumberCanReach(input, size, 1, 1, 1); cout << largestNumber << endl; delete[] input; return 0; }
This problem looks like a harder version of the LeetCode program "frog jump". Forget about the array or dynamic programming for a while and look at it conceptually. A state S is (n,k) where n is an element of the input array, and k the difference to the previous number. The initial state S0 is (0, 1). Successor states (n', k') are then (n + k - 3, k - 3), (n + k, k), (n + k + 1, k + 1), (n + k + 2, k + 2), assuming that n' is an element of the array and n' > n. States thus form a graph, and the question boils down to finding all successor states reachable from S0 and returning the state with the largest n. In terms of C++, you need a couple of ingredients: a std::set<int> in_array that tells whether a given number is part of the input array. This gives you O(log n) lookups. You could also use an std::unordered_set. a type State that represents a state (n, k). You can use a struct or a std::pair<int, int>. a std::set<State> seen that keeps track of visited states a std::stack<State> todo that represents a list of states to visit The main program is then a loop that takes an element from the stack and checks if the state has been visited already. If not, it marks the state as visited and adds the successors to the todo list. When the stack becomes empty, take the highest element of seen. This is the largest array element reachable. With all this, problem 3 without any extra compiler optimizations takes 30 ms on my system.
74,548,280
74,581,323
Executing external python file from inside ns3
I have a python file, containing a pre-trained model. How can I execute this file from inside ns-3 code? The python file will start execution when enough amount of data is gerenerated by the ns-3, which will be given to the pre-trained model. Later, the model predicts one value and it is used in ns-3 during simulation. I tried Calling Python script from C++ and using its output. It is not helpful in my case. I am expecting to execute only python file from ns-3.
In my case, I have tried the following piece of code in a function where I was required to execute the external python file from ns-3. This specific example is for the Ubuntu environment. system("/[path_to_your_python]/anaconda3/bin/python /[path_to_your_inference_file]/inference.py"); Note: The inference.py file will be executed whenever the C++ function is called, making the simulation too time-consuming compared to normal circumstances. Suggestion: I would suggest using ONNX.
74,548,284
74,548,515
How to overload class method with two template parameters, so I can use std::function as one of them?
I need some help with working with templates. I have code like this, it's class holding two vectors of std::function object, and a method that pushes some function (bind, lambda, or functor) in one of them: typedef std::function<int(int)> unFuncPtr; typedef std::function<int(int, int)> binFuncPtr; class Operations { public: template <size_t argsCount, class T> void RegisterOperator(T fn) { if (argsCount == 1) { m_unaryOperations.push_back(fn); } if (argsCount == 2) { m_binaryOperations.push_back(fn); } } private: std::vector<unFuncPtr> m_binaryOperations; std::vector<binFuncPtr> m_unaryOperations; I wanted this code to push, for example, lambda with two argements in m_binaryOperations or lambda with only one argument to m_unaryOperations calling method RegisterOperator like this: Operations operations; operations.RegisterOperator<1>([](int x) {return x * x; }) operations.RegisterOperator<2>([](int x, int y) {return x + y; }) But it gives me a funtion-style-cast error. As I understand it's because of interpreting class T in two different ways in one function. How can I modify the code to call the method with template parameter 1 or 2 for argsCount, so it will be known what type is class T and to what vector function from the argument must be pushed? I tried different ways to solve this problem. The first one is to overload templates inside the class like this: template <size_t argsCount, class T> void RegisterOperator(T fn) { } template<> void RegisterOperator<1>(unFunPtr fn) { m_unaryOperations.push_back(fn); } template<> void RegisterOperator<2>(binFunPtr fn) { m_binaryOperations.push_back(fn); } But debugging showed me that it won't even go inside overloaded functions with the examples I wrote upper in question. The second one is to overload templates inside the class like this: template<class T = unFunPtr> void RegisterOperator<1>(T fn) { m_unaryOperations.push_back(fn); } template<class T = binFunPtr> void RegisterOperator<2>(T fn) { m_binaryOperations.push_back(fn); } I thought the default template lets me define only argsCount in the template when I'm calling the method, but it causes a lot of errors. Hoping for your help.
First, you have a typo here: std::vector<unFuncPtr> m_binaryOperations; std::vector<binFuncPtr> m_unaryOperations; It should be: std::vector<unFuncPtr> m_unaryOperations; std::vector<binFuncPtr> m_binaryOperations; Second, even then it wouldn't compile, since with "ordinary" if, both branches needs to be compilable. You can resolve the problem with if constexpr if you have C++17 available: void RegisterOperator(T fn) { if constexpr (argsCount == 1) m_unaryOperations.push_back(fn); if constexpr (argsCount == 2) m_binaryOperations.push_back(fn); } Live demo: https://godbolt.org/z/bbqs7Knbd
74,549,189
74,549,327
Why CMake does not propagate the PUBLIC include directories between libraries?
I have a C++ project with three shared libraries, let's call them libA, libB and libC. libA is dependant to both libB and libC. All of these three libraries are located inside a folder called utilities. Here is what I have: Root CMakeLists.txt file: cmake_minimum_required (VERSION 3.20) # Required because of policy CMP0074 project(Test VERSION 2022) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) file(TO_CMAKE_PATH $ENV{SHARED_PATH} SHARED_PATH) add_subdirectory (utilities) for libB I have the CMakeLists.txt like this: add_library(libB SHARED inc/libB.h inc/libBExport.h src/libB.cpp ) target_include_directories(libB PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/inc PUBLIC ${SHARED_PATH}/inc ) target_compile_definitions(libB PRIVATE LIBB_DLL) and the same goes for libC: add_library(libC SHARED inc/libC.h inc/libCExport.h src/libC.cpp ) target_include_directories(libC PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/inc PUBLIC ${SHARED_PATH}/inc ) target_compile_definitions(libC PRIVATE LIBC_DLL) Now, the CMakeLists.txt file for libA is like this: add_library(libA SHARED inc/libA.h inc/libAExport.h src/libA.cpp ) target_include_directories(libA PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/inc PUBLIC ${SHARED_PATH}/inc ) target_link_directories(libA PUBLIC libB PUBLIC libC ) target_compile_definitions(libA PRIVATE LIBA_DLL) Now, I generate the Visual Studio solution file using cmake: > cmake -G "Visual Studio 16 2019" -A x64 Everything goes fine. But when opening the solution with VS2019, libB and libC are compiling fine, but libA cannot be compiled with this error: D:\code\proj\utilities\inc\libA.h(5,10): fatal error C1083: Cannot open include file: 'libB.h': No such file or directory D:\code\proj\utilities\inc\libA.h(9,10): fatal error C1083: Cannot open include file: 'libC.h': No such file or directory Can someone explain me why the the PUBLIC include directories of libB and libC are not inherited to libA?
Instead of the following: target_link_directories(libA PUBLIC libB PUBLIC libC ) You should use target_link_libraries(). target_link_libraries(libA PUBLIC libB PUBLIC libC ) This will setup a dependency between the libraries which sets the include path, compiler settings, additional link directories, and additional link libraries.
74,549,582
74,602,211
Fail to import QML module using CMake
I'm currently building a minimalist app following this CMake architecture: -root --QmlModule ---Component1.qml ---Component2.qml --App1 ---main.cpp ---main.qml --App2 ---main.cpp ---main.qml I use "qt6_add_qml_module" to create a QML module at "QmlModule" level as a STATIC library. qt_add_library(myComponentTarget STATIC) qt6_add_qml_module(myComponentTarget URI QmlModule VERSION 1.0 QML_FILES Component1.qml Component2.qml RESOURCES logo.png) Then, at App1 (and App2) level, a link to the module is done using "target_link_libraries". "qt6_add_qml_module" does some work behind the scenes in order to expose the module trough an automatically generated plugin named "your_component_URIplugin". More details about this here. add_executable(App1Exe main.cpp) qt6_add_qml_module(App1Exe URI App1 VERSION 1.0 QML_FILES main.qml) target_link_libraries(App1Exe PRIVATE myComponentURIplugin) At Root level, I overload QML_IMPORT_PATH in order to link to the build folder and add all subdirectories. set(QML_IMPORT_PATH ${CMAKE_CURRENT_SOURCE_DIR}/qmlModule) add_subdirectory(QmlModule) add_subdirectory(App1) add_subdirectory(App2) I run CMake without any errors, and open App1/main.qml file. On my import QmlModule, the module can't be found: module "lupinComponentsplugin" is not installed How to make my module visible from my Apps ? What step am I missing ?
CMake itself was fine, this was a runtime error and not a link error. This issue was raised because the QQmlApplicationEngine wasn't finding path towards my module's QMLDIR. In the end, the only thing missing was an additional import path ":/" in QQmlEngine: QQmlApplicationEngine engine; engine.addImportPath(":/");
74,549,928
74,550,353
Concept for constraining parameter pack to string-like types or types convertible to string
I'm piecing together a C++20 puzzle. Here's what I want to do: Function append_params will concatenate the url together with additional query parameters. To make design this in a dynamic and extensible way, I wanted to write a concept such that it allows types that an std::string can be constructed from it allows types convertible to string using std::to_string() template<typename... Ts> requires requires(T a) { std::to_string(a); } auto append_params(std::pmr::string url, Ts... args) { } it works for a pack of parameters I've found useful information on point 2) here. However, for point 1) and 3) I'm rather clueless (I'm also new to concepts). How can I constrain the whole parameter pack (what's the syntax here?) and how can I make sure that from every parameter I can construct an std::string object? Also, I would have to know at compile time if I want to use std::strings constructor or std::to_string to handle the case.
When developing a concept, always start with the template code you want to constrain. You may adjust that code at some point, but you always want to start with that code (unconstrained). So what you want is something like this: template<typename... Ts> auto append_params(std::string &url, Ts... &&args) { return (url + ... + std::forward<Ts>(args) ); } This doesn't work if any of the types in args are not std::strings or something that can be concatenated with std::string. But you want more. You want to take types which std::to_string can be used on. Note that this is a pretty bad interface, since std::to_string cannot be extended by the user. They can make their types convertible to std::string or some other concatenate-able string type like string_view. But users cannot add overloads to std library stuff, so they can't make a type to_stringable. Regardless, to allow to_string to work, we would need to change the code to concatenate with this expression: std::to_string(std::forward<Ts>(args)). But that would only take types that to_string works on, not types convertible to a string. So what we need is a new function which will use to_string if that is appropriate or just return the original expression if it can be concatenated directly. So we have two kinds of types: those that are inherently string-concatenatable, and those which are to_string-able: template<typename T> concept is_direct_string_concatenatable = requires(std::string str, T t) { {str + t} -> std::same_as<std::string>; }; template<typename T> concept is_to_stringable = requires(T t) { {std::to_string(t)} -> std::same_as<std::string>; }; //Combines the two concepts. template<typename T> concept is_string_concatenable = is_direct_string_concatenatable<T> || is_to_stringable <T>; template<is_string_concatenable T> decltype(auto) make_concatenable(T &&t) { //To_string gets priority. if constexpr(is_to_stringable<T>) return std::to_string(std::forward<T>(t)); else return std::forward<T>(t); } So now your template function needs to use make_concatenable and the concept: template<is_string_concatenable ...Ts> auto append_params(std::string url, Ts&& ...args) { return (url + ... + make_concatenable(std::forward<Ts>(args))); }
74,550,010
74,551,754
error C2660: 'std::pair<a,b>::pair': function does not take 2 arguments
I am trying to create a structure and insert that a map as following: struct Queue_ctx { std::mutex qu_mutex; std::condition_variable qu_cv; std::queue<std::vector<std::byte>> qu; }; std::map<std::string, Queue_ctx> incoming_q_map; Queue_ctx qctx; std::vector<std::byte> vect(100); qctx.qu.push(vect); incoming_q_map.emplace("actor", qctx); But I get the following error : error C2660: 'std::pair<const std::string,main::Queue_ctx>::pair': function does not take 2 arguments message : see declaration of 'std::pair<const std::string,main::Queue_ctx>::pair' message : see reference to function template instantiation 'void std::_Default_allocator_traits<_Alloc>::construct<_Ty,const char(&)[6],main::Queue_ctx&>(_Alloc &,_Objty *const ,const char (&)[6],main::Queue_ctx &)' being compiled with [ _Alloc=std::allocator<std::_Tree_node<std::pair<const std::string,main::Queue_ctx>,std::_Default_allocator_traits<std::allocator<std::pair<const std::string,main::Queue_ctx>>>::void_pointer>>, _Ty=std::pair<const std::string,main::Queue_ctx>, _Objty=std::pair<const std::string,main::Queue_ctx> ] AFAIU, emplace constructs the element inplace. if that is true then why compiler is trying to create pair to emplace? I see that the syntax of pair synthesized by the compiler is odd that's why it complains. But why does that happen and what can I do to fix this problem ? I tried to pass make_pair() explicitly but that did not help. If I comment the qu_mutex and qu_cv then I am able to do emplace. What does error has to do with these two members? Isn't the case that default consutructor initializing the members of struct ? I know copy/assignment/move constructors are deleted by the compiler.
Anyway to fix this problem you need customize copy constructor and assignment operator. Also mutex suggest some synchronization of qu in all scenerios, so all fields should be private (so struct should be changed to class). class Queue_ctx { mutable std::mutex qu_mutex; std::condition_variable qu_cv; std::queue<std::vector<std::byte>> qu; public: Queue_ctx() = default; Queue_ctx(const Queue_ctx& other) : Queue_ctx(other, std::scoped_lock{ other.qu_mutex }) { } Queue_ctx(const Queue_ctx& other, const std::scoped_lock<std::mutex>&) : qu { other.qu } { } Queue_ctx(Queue_ctx&& other) : Queue_ctx(std::move(other), std::scoped_lock{ other.qu_mutex }) { } Queue_ctx(Queue_ctx&& other, const std::scoped_lock<std::mutex>&) : qu { std::move(other.qu) } { } Queue_ctx& operator=(const Queue_ctx& other) { std::scoped_lock lock{ qu_mutex, other.qu_mutex }; qu = other.qu; return *this; } Queue_ctx& operator=(Queue_ctx&& other) { std::scoped_lock lock{ qu_mutex, other.qu_mutex }; qu = std::move(other.qu); return *this; } void push(const std::vector<std::byte>& v) { std::unique_lock lock{ qu_mutex }; qu.push(v); } void push(std::vector<std::byte>&& v) { std::unique_lock lock{ qu_mutex }; qu.push(std::move(v)); } }; https://godbolt.org/z/xn6orTedz It compiles, but more testing is required. Note some functionality is missing to utilize qu_cv.
74,550,744
74,552,124
How does `std::is_const` work on non-static member method types?
Question: How does std::is_const work on non-static member method types? Is a const member method not a const-qualified type? Example: class D {}; We will have std::is_const_v<void (D::*)() const> == false Follow-up: Can the constness of a member non-static method be determined (at compile/run time)?
In C++, functions are not first-class citizens: you can't have objects with function type (you can have function objects, but that's a different concept). void (D::*)() const is a pointer type. std::is_const will tell you whether the pointer is const or not, so: std::is_const_v<void (D::*)() const> == false; std::is_const_v<void (D::* const)()> == true. There is no standard trait to check whether a member function has a const qualifier. However, you can make your own. François Andrieux's answer would be the traditional way of doing that, but as mentioned in the comments, you need 48 specializations to make it complete. Here is another, perhaps more concise way: #include <type_traits> struct ArbitraryType { template <typename T> operator T & (); template <typename T> operator T && (); }; template<bool, bool, class T, class Arg, class... Args> struct is_invocable_with_const_first_arg_impl : std::bool_constant< is_invocable_with_const_first_arg_impl< std::is_invocable_v<T, Arg const&, Args...> || std::is_invocable_v<T, Arg const&&, Args...>, std::is_invocable_v<T, Arg&, Args...> || std::is_invocable_v<T, Arg&&, Args...>, T, Arg, Args..., ArbitraryType >::value > {}; template<bool b, class T, class Arg, class... Args> struct is_invocable_with_const_first_arg_impl<true, b, T, Arg, Args...> : std::true_type {}; template<class T, class Arg, class... Args> struct is_invocable_with_const_first_arg_impl<false, true, T, Arg, Args...> : std::false_type {}; template<class T, class Arg> struct is_invocable_with_const_first_arg : is_invocable_with_const_first_arg_impl<false, false, T, Arg> {}; template<class T, class Arg> inline constexpr bool is_invocable_with_const_first_arg_v = is_invocable_with_const_first_arg<T, Arg>::value; template<class T> struct is_const_member_func_ptr; template<class R, class C> struct is_const_member_func_ptr<R C::*> : std::bool_constant< is_invocable_with_const_first_arg_v<R C::*, C> || is_invocable_with_const_first_arg_v<R C::*, C> > {}; template<class T> inline constexpr bool is_const_member_func_ptr_v = is_const_member_func_ptr<T>::value; Demo
74,551,228
74,551,310
Correct interface for a function on a base class and inherited class?
I have defined a base class DiGraph and a inherited class UnGraph as: class DiGraph { protected: long V; // No. of vertices; Vertices are labelled from 0, 1, ... V-1. vector<list<long>> adj; // Adjacency List of graph public: DiGraph(long V); // Constructor, initialize V and resize adj; virtual void addEdge(long v, long w); // Add directed edge (v,w) to adj vector<list<long>> getadjL (); // Returns the adjacency list vector<vector<long>> getadjM (); // Computes and returns the adjacency matrix }; class UnGraph: public DiGraph { public: void addEdge(long v, long w); // Add undirected edge i.e add (v,w) and (w,v) }; I have defined multiple functions with return value (and sometime arguments) as DiGraph such as: DiGraph Kn (long n) { // Returns the complete graph on n vertices DiGraph G(n); for (long i = 0; i < n ; i++) { for (long j = 0; j < n; j++) G.addEdge(i, j); } return G; } Now I want the 'equivalent' versions of these functions for UnGraph (i.e. the same function except the 'addEdge' function of DiGraph should be replaced with the 'addEdge' function of UnGraph and the class types should be changed. Do I have to make another copy of this function (for all the functions I have), or is it possible to write a single function for both base and inherited class? I though of using function templates but then realized that you if you generalize a class T such as: template <typename T> T Kn (long n) { // Returns the complete graph on n vertices T G(n); for (long i = 0; i < n ; i++) { for (long j = 0; j < n; j++) G.addEdge(i, j); } return G; } but then realized you can't use any of it's fields like T.addEdge(u,v) in the function body. Any ideas?
As long as you provide a constructor for UnGraph that accepts a long, e.g. UnGraph(long V) : DiGraph(V) {} you can implement Kn as a template function taking GraphType as template parameter (e.g. DiGraph or UnGraph): template <typename GraphType> GraphType Kn (long n) { GraphType G(n); for (long i = 0; i < n ; i++) { for (long j = 0; j < n; j++) G.addEdge(i, j); } return G; } and use it like DiGraph completeDi = Kn<DiGraph>(4); UnGraph completeUn = Kn<UnGraph>(4); That compiles for me.
74,551,508
74,551,566
Determine the return type of a callable passed to a template
I have a simple wrapper template that allows free functions (e.g. open() close() etc) to passed as template parameters. The code is as follows: template <auto fn, typename ReturnType=void> struct func_wrapper { template<typename... Args> constexpr ReturnType operator()(Args&&... args) const { if constexpr( std::is_same<ReturnType, void>::value) { fn(std::forward<Args>(args)...); } else { return fn(std::forward<Args>(args)...); } } }; This is used as follows: void CloseFunc2(int a); into OpenFunc2(const std::string&, int flags); using FileWrapper2 = DevFileWrapper<func_wrapper<OpenFunc2, int>, func_wrapper<CloseFunc2>>; The code is working fine but I would like to remove the requirement to manually specify ReturnType when creating a func_wrapper. I tried using std::result_of but that failed because fn is a non type template parameter, e.g.: template<typename... Args> constexpr auto operator()(Args&&... args) const -> std::invoke_result<fn(std::forward<Args>(args)...)>::type { if constexpr( std::is_same<ReturnType, void>::value) { fn(std::forward<Args>(args)...); } else { return fn(std::forward<Args>(args)...); } } the error is: template-parameter-callable.cpp:48:71: error: template argument for template type parameter must be a type constexpr auto operator()(Args&&... args) const -> std::invoke_result<fn(std::forward<Args>(args)...)>::type { ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/ usr/include/c++/v1/type_traits:4009:17: note: template parameter is declared here template <class _Fn, class... _Args> ^ 1 error generated. How can I deduce the return type of calling fn at compile time?
template <auto fn> struct func_wrapper { template<typename... Args> constexpr decltype(auto) operator()(Args&&... args) const { return fn(std::forward<Args>(args)...); } }; have you tried this? I think that works in c++17. Definitely in c++20. The return type of a callable cannot be determined unless you also know the arguments you are calling it with. I can extract the return type, but I don't think you need it. template <auto fn> struct func_wrapper { template<typename... Args> constexpr decltype(auto) operator()(Args&&... args) const { using ReturnType = std::invoke_result_t< decltype(fn), Args&&... >; return fn(std::forward<Args>(args)...); } }; but as you can see we don't need it. return f(x) when f returns void is (now) legal.
74,551,553
74,576,258
CMAKE SFML found but depencencies missing
I know this question has been asked before but following the answer or other online resources I came across yielded nothing. I've built SFML from source for Windows using CMAKE GUI and mingw32-make. I've changed it from making shared to static libraries. On the SFML site, it states that the dependencies are included under Windows but after I added the files to my project and changed the CMakeList to include SFML it gives an error that SFML is found but its dependencies are not. SFML found but some of its dependencies are missing (FreeType OpenAL VorbisFile VorbisEnc Vorbis Ogg FLAC) To include SFML I have the following in CMake: set(SFML_STATIC_LIBRARIES TRUE) # I've build static libraries set(SFML_DIR ${CMAKE_CURRENT_SOURCE_DIR}/ext/SFML/cmake) # Contains the CMake files for SFML find_package(SFML 2.5 COMPONENTS system window graphics network audio REQUIRED) # Using v2.5.1 set(SFML_LIBS libsfml-audio-s libsfml-graphics-s libsfml-main libsfml-network-s libsfml-system-s libsfml-window-s ) target_link_libraries(${PROJECT_NAME} ${SFML_LIBS}) I've tried to add the dependencies in CMake: set(SFML_DEPENDENCIES libFLAC libfreetype libogg libopenal32 libvorbis libvorbisenc libvorbisfile ) target_link_libraries(${PROJECT_NAME} ${SFML_LIBS} ${SFML_DEPENDENCIES}) But this did not change the outcome. I've looked through the source files and found the missing libraries in extlibs but copying these does not help (or I've placed them in the wrong place) Do I need to get the dependencies myself and where should I put these?
The issue was that after building it and moving it over to the project I placed the files in the wrong place. So it could not find them. Here is how I did it. I built it using CMake and mingw32-make from the source, changing the settings from dynamic to static built. After this, I moved the files to a folder in my project. Built statically, you also need to get the required files from the source and place them in the lib folder. To add it in the project I changed the CMakeList.txt in my project to the following: cmake_minimum_required(VERSION 3.23) set(CMAKE_CXX_STANDARD 23) # Setup project(main) # Must match the main file name set(EXECUTABLE_NAME "Test") # Executable name set(project_headers #logger.hpp # Custom logger ) set(project_sources ${PROJECT_NAME}.cpp #logger.cpp # Custom logger ) include_directories( # dirs to include ext/SFML/include/ ) link_directories( # dirs to link ext/SFML/lib/ ) # SFML set(SFML_STATIC_LIBRARIES TRUE) set(SFML_DIR ext/SFML/lib/cmake) find_package(SFML 2.5 COMPONENTS system window graphics network audio REQUIRED) set(SFML_LIBS sfml-audio-s sfml-graphics-s sfml-network-s sfml-system-s sfml-window-s ) # Build add_executable(${EXECUTABLE_NAME} ${PROJECT_NAME} ${project_sources} ${project_headers}) target_link_libraries(${PROJECT_NAME} ${SFML_LIBS}) EDIT Forgot the dependencies: set(SFML_DEPENDENCIES opengl32 # window, graphics winmm # window, system gdi32 # window freetype # graphics openal32 # audio FLAC # audio vorbis # audio vorbisfile # audio vorbisenc # audio ogg # audio ws2_32 # network ) target_link_libraries(${PROJECT_NAME} ${SFML_LIBS} ${SFML_DEPENDENCIES}) # SFML first, dependencies second
74,551,793
74,616,018
Pointer offset is incorrect when using multiple inheritance
I am encountering a bug in some code which uses multiple inheritance when accessing a member variable. Unfortunately, I cannot provide a minimum reproducible example that you can run, but I can provide a bunch of information as to what I am seeing. My code is compiled using GCC for ARM. To give the rough idea, this is what I have (not my actual code): class Foo; class MyClass: public A, public B, public C { public: Foo& foo() { assert(_ptr); return *_ptr; } private: //A bunch of other members std::unqiue_ptr<Foo> _ptr; //Located 0x2710 from start of this }; Where classes A, B, and C also multiply inherit from other classes. For example: class A : public Q, public R, public S { //Data members and functions... }; I have a pointer to MyClass as follows: MyClass* myClassPtr; //Points to 0x20005c98 Where the address of myClassPtr->_ptr should be 0x200083A8 (0x20005c98 + 0x2710) However, when I step through my assembly, this is what I see 0800883a: ldr r6, [r6, #4] 0800883c: add.w r3, r4, #94208 ; 0x17000 08008840: str.w r6, [r3, #3308] ; 0xcec 08008844: add.w r3, r6, #8192 ; 0x2000 08008848: ldr.w r3, [r3, #1532] ; 0x5fc The str.w is the place at which my myClassPtr is getting set, thus r6 should hold the address to the start of my MyClass instance. Which I can verify to be true (r6 holds 0x20005c98). The instruction at 08008844 (add.w) should then be moving to the appropriate offset within the unique_ptr in order to check if it is null. However, 0x20005c98 + 0x2000 is 0x20007C98 which is well BEFORE the start of the _ptr variable... I've tried with multiple versions of the compiler as well just to make sure this wasn't a bug. Thus, I know its my fault and that the problem is related to the multiple inheritance, but I just can't figure out what the problem actually is. Some general insight into what to look for/test would be very helpful. By the way, I call the same function (the bool cast operator of the pointer) within the constructor of MyClass. It generated the following assembly: 0802f5a2: add.w r3, r4, #8192 ; 0x2000 0802f5a6: ldr.w r5, [r3, #1812] ; 0x714 In this case, r4 is holding the this pointer, but otherwise it is identical to the other call to the function except that this time, the offset is correct...
For anyone else experiencing a problem like this, it cam down to a violation of the "One Definition Rule" caused by differing #define values in translation units. For example, if the class definition was: Foo.hpp: class Foo { private: std::array<uint8_t, MAX_BUFFER_SIZE> _buffer; int _foo; }; File A.cpp had MAX_BUFFER_SIZE defined as 10 when including Foo.hpp File B.cpp had MAX_BUFFER_SIZE defined as 20 when including Foo.hpp Thus the address of _foo differs between A.cpp from B.cpp, resulting in inconsistent assembly code. In my actual application, the actual cause of the problem was a bit more involved (due to a typo in some include files), but it distilled down to this.
74,552,485
74,553,107
Initialize deprecated field without tripping warning
I have a struct with a static field I want to deprecate. However, for now I still want to initialize it. The following snippet produces a warning under MSVC and GCC (but not Clang): struct A { ~A(); }; struct B { [[deprecated]] static A X; }; A B::X; //warning C4996: 'B::X': was declared deprecated Interestingly, if I remove ~A();, the warning disappears. Is there way to initialize B::X without producing a warning, without resorting to hacky pragmas or such?
The warning disappears when you remove the destructor because then A can be trivially destructed (and also constructed), meaning that the compiler doesn't need to emit actual code to initialize anything, and thus does not generate code that references B::X. Therefore, there is no trigger to emit the warning. This also hints at a possible workaround: Make B::X something "trivial", e.g. a reference. For example (live on godbolt): struct A { ~A(); }; struct B { static A helper; [[deprecated]] static A & X; }; A B::helper; A & B::X = B::helper; This does not produce the warning, only where it is actually used. And in most cases, this workaround should not change the semantics of your program. As a side note, the static members are initialized in the order of their definition, see e.g. this answer.
74,553,216
74,553,360
Hello! My algorithm does not work for n>7 and I don't know why
I built a perfectly balaced tree using BUILD_TREE and printed it inOrder and using a PRETTY_PRINT. The keys for my tree are in a sorted array named arr and I use n as the number of keys. If I give n a value bigger that 7 it does not print anything and I don't understand why. I need it to work for n=11. #include <stdio.h> #include <stdlib.h> #define NR_SPATII 7 #define MAX_SIZE 20 using namespace std; typedef struct Tree { int key; struct Tree* left; struct Tree* right; int size; }Tree; Tree* createNewNode(int givenkey) { Tree* node = (Tree*)malloc(sizeof(Tree)); node->key = givenkey; node->left = NULL; node->right = NULL; node->size = NULL; return node; } Tree* BUILD_TREE(int arr[], int low, int high) { int s = 1; if (low > high) return NULL; int mid = (low + high) / 2; Tree* node = createNewNode(mid); node->left = BUILD_TREE(arr, low, mid - 1); node->right = BUILD_TREE(arr, mid + 1, high); if (low == high) node->size = 1; else node->size = node->left->size + node->right->size + 1; return node; } void PRETTY_PRINT(Tree* root, int nivel) { if (root == NULL) return; nivel += NR_SPATII; //crestem distanta intre nivele PRETTY_PRINT(root->right, nivel);//procesam copilul drept printf("\n"); for (int i = NR_SPATII; i < nivel; i++) printf(" "); printf("%d,%d\n", root->key, root->size);//scriem nodul dupa spatiu PRETTY_PRINT(root->left, nivel); } void inOrder(Tree* root) { if (root != NULL) { inOrder(root->left); printf("%d,%d ", root->key, root->size); inOrder(root->right); } } void demo() { int n = 7; int arr[MAX_SIZE]; for (int i = 1; i <= n; i++) arr[i] = i; Tree* root = (Tree*)malloc(sizeof(Tree)); root = BUILD_TREE(arr, 1, n); printf("AFISARE INORDINE:\n"); inOrder(root); printf("\nAFISARE PRETTY PRINT:"); PRETTY_PRINT(root, 0); } int main() { demo(); return 0; }
Running your program in a debugger should instantly identify the problem as this line in BUILD_TREE: else node->size = node->left->size + node->right->size + 1; The issue is that the left or right pointers can be NULL. If they are, you will most likely crash. Dereferencing a NULL pointer and reading (or writing) to that memory is undefined behavior. You can replace this: if (low == high) node->size = 1; else node->size = node->left->size + node->right->size + 1; With this: node->size = 1 + (node->left ? node->left->size : 0) + (node->right ? node->right->size : 0); That means if a subtree is NULL, it will be considered to have size zero, and crucially you will not dereference that pointer. Alternatively you can define a function that returns a tree size and handles NULL-testing internally: int TreeSize(const Tree* tree) { return tree ? tree->size : 0; } Then your calculation becomes a bit neater: node->size = 1 + TreeSize(node->left) + TreeSize(node->right);
74,553,352
74,553,573
"expression is not assignable" when trying to assign a value to an element of an array of arrays
I created the following: //main.cpp const int size = 3; int field[size][size] = {{0}}; int (*pfield)[size] = field; A class of mine wants to set a value within a function: //userInputs.cpp int UserInputs::setValue(int (*field)[3], int x, int y) { ... ((*field)[x] + y) = value; ... } And it causes the following error: src/userInputs.cpp:15:26: error: expression is not assignable ((*field)[x] + y) = value; As far as my understanding goes should ((*field)[x] + y) = value; give me access to the to the value. Obviously, that's not the case and my issue is me not really understanding what went wrong. Not really experienced in C++ and pointers. I appreciate any answers and/or explanations.
If you break down ((*field)[x])+y you can see why it's unassignable. C expressions are roughly read inside out so we start with (*field), which is the same as field[0], then tack on [x] and you have field[0][x], which is still an l-value (assignable, i.e., can be on the left hand side of an =). Then tack on the + y and you have field[0][x] + y, which is now y added to the value at field[0][x] so is now an r-value (not assignable). If you want to fix it and keep the form roughly the same, the * needs to move out of the (()). That is, *(field[x]+y) = value; Or more simply as field[x][y] = value;
74,553,543
74,566,441
How to declare function using reference?
I am making this program to check the alphabetic and numeric characters of a C-type string. I am using C-type strings because it is for an assignment, otherwise I would opt to use std::string. How do I declare the function? In my case, I want str, SAlpha and SNum, to be stored in the function as s, alpha, num. That's why I am using references, but I don't understand how to declare it without giving me an error saying undefined. I have been searching, but I am new to functions, and don't understand them quite well. That's why I'm asking. Below is the code: #include <iostream> #include <cstring> #include <cctype> using namespace std; void seperate(char (&s)[], char (&alpha)[], char (&num)[]); int main() { char str[100]; char SAlpha[100]; char SNum[100]; cout << "Insert a string: "; cin.getline(str,100); strcpy(SAlpha, str); strcpy(SNum,str); cout << "Alphabetic characters " << endl; for (int i = 0; i < strlen(SAlpha); i++) { if (isalpha(SAlpha[i])) { cout << " " << SAlpha[i]; } } cout << endl; cout << "Numeric characters " << endl; for (int i = 0; i < strlen(SNum);i++) { if (isdigit(SNum[i])) { cout << " " << SNum[i]; } } seperate(str, SAlpha, SNum); //UNDEFINED FUNCTION return 0; }
You are getting an "undefined" error because you have only declared the seperate() function but have not implemented it yet, eg: #include <iostream> #include <cstring> #include <cctype> using namespace std; // THIS IS JUST A DECLARATION!!! void seperate(char (&s)[100], char (&alpha)[100], char (&num)[100]); int main() { char str[100]; char SAlpha[100]; char SNum[100]; cout << "Insert a string: "; cin.getline(str,100); strcpy(SAlpha, str); strcpy(SNum,str); cout << "Alphabetic characters " << endl; for (int i = 0; i < strlen(SAlpha); i++) { if (isalpha(SAlpha[i])) { cout << " " << SAlpha[i]; } } cout << endl; cout << "Numeric characters " << endl; for (int i = 0; i < strlen(SNum);i++) { if (isdigit(SNum[i])) { cout << " " << SNum[i]; } } seperate(str, SAlpha, SNum); // <-- OK TO CALL SINCE THE FUNCTION IS DECLARED ABOVE... return 0; } // ADD THIS DEFINITION!!! void seperate(char (&s)[100], char (&alpha)[100], char (&num)[100]) { // do something here... }
74,553,866
74,553,911
"Class template has already been defined" when making similar but different specializations
I have two class specializations. I want one of them to be used when T::A exists and the other to be used when T::B exists, which should be multually exclusive in practice. I am using std::void_t< decltype( ... ) > to test for existence. I expect that expression to fail to evaluate for either one or the other specialization, and so I expect SFINAE to cause one of the specializations to be ignored. template< typename T, typename Enable = void > class C{}; template< typename T > class C< T, std::void_t< decltype( T::A ) > > {}; template< typename T > class C< T, std::void_t< decltype( T::B ) > > {}; However, MSVC just gives me (On line containing T::B): error C2953: 'C<T,void>': class template has already been defined (On line containing T::A): note: see declaration of 'C<T,void>' What am I doing wrong?
Clang also rejects this code, but not GCC. This is not the first time I'm seeing problems with std::void_t. I would stay away from it, and prefer decltype(void(T::A)). Or you can define your own robust void_t (code taken from cppreference): template<typename... Ts> struct make_void { typedef void type; }; template<typename... Ts> using void_t = typename make_void<Ts...>::type;
74,554,333
74,554,813
How to clear std::ofstream file buffer?
I am making a console text editor that continuously saves its content to a text file as text is being written to the editor. FileEditor editor("C://temp/test.txt"); while (true) { if (_kbhit()) { editor.keypress(_getche()); system("cls"); std::cout << editor.content(); editor.save(); } } In order to directly save the written content to the text file without having to close() and reopen() the file everytime, I flush the ofstream file buffer directly after inserting text into it. class FileEditor { private: std::ofstream _file; std::string _content; public: // ... void save() { _file << _content << std::flush; } // ... }; The problem is when I write multiple characters into the console, for example the string abcd, it will write a to the file, then aab, adding ab to the current buffer content, then aababc, and so on. Therefore, I wish to clear the ofstream file buffer to replace its contents instead of continuously adding new text to the buffer. Is there a method for clearing the file buffer? Is there a better way of doing what I'm trying to achieve? I tried finding a method for clearing the buffer and I tried searching online for anyone who might've had the same problem as me, but to no avail.
The problem is when I write multiple characters into the console, for example the string abcd, it will write a to the file, then aab, adding ab to the current buffer content, then aababc, and so on. Your problem has nothing to do with the file buffer. You are not clearing the editor buffer after writing it to the file, so you are writing the same characters to the file over and over. The user types a, so your editor buffer is a, and you write a to the file. Then, the user types b, so your editor buffer is now ab, and you write ab to the file. Then, the user types c, so your editor buffer is now abc, and you write abc to the file. Then, the user types d, so your editor buffer is now abcd, and you write abcd to the file. And so on. You need to write only the new characters that have entered the editor buffer since the last write to the file. For instance, maintain an index into the editor buffer where the last file write left off, and then have the next file write pick up from that index and advance it for the next file write, etc. Therefore, I wish to clear the ofstream file buffer to replace its contents instead of continuously adding new text to the buffer. Is there a method for clearing the file buffer? Is there a better way of doing what I'm trying to achieve? The only way to do this with ofstream is to close the re-open the file stream so that the current file content can be truncated. Otherwise, you will have to resort to using platform-specific APIs to truncate the file without closing it first.
74,554,343
74,555,355
The correct variant of implementation of the server-client in one application? Qt6
I am creating simple online chat with server and client in one application. I wrote client-side, but i don't know how will be correct use QTcpServer. Need i create QTcpServer in new thread? So that I can connect to it as a client from this application. If yes, how do it? Or it's useless and not needed idea? Need i create new thread for every new connection in order to process it? I am developing a chat as a course project for a university
Assuming you are using Qt's networking APIs, you don't need to use multiple threads. The reason is that Qt's APIs are designed around a non-blocking event-loop model, so it is expected that no function-call should ever take more than a negligible amount of time (e.g. a few milliseconds) to return, after which the main thread's QEventLoop resumes execution and can therefore handle other tasks in a timely manner, all from within a single thread. That said, there are a few optional methods in the Qt API that are blocking, and in a single-threaded application, calling those methods risks making your application un-responsive for (however long it takes for those methods to return). Fortunately those methods aren't necessary, and they are clearly documented. I recommend avoiding them, as there are always better, non-blocking ways to achieve the same result in Qt, e.g. by connecting the appropriate signals to the appropriate slots. To sum up: threads aren't necessary in Qt-based networking, and your program will be simpler, more reliable, and easier to debug if you don't use threads. When implementing server-like functionality, a QTcpServer object is useful; you might want to have a look at this example program for cues on how to use it.
74,554,719
74,554,816
Boost asio:async_read() using boost::asio::use_future
When calling asio::async_read() using a future, is there a way to get the number of bytes transferred when a boost:asio::error::eof exception occurs? It would seem that there are many cases when one would want to get the data transferred even if the peer disconnects. For example: namespace ba = boost::asio; int32_t Session::read (unsigned char* pBuffer, uint32_t bufferSizeToRead) { // Create a mutable buffer ba::mutable_buffer buffer (pBuffer, bufferSizeToRead); int32_t result = 0; // We do an async call using a future. A thread from the io_context pool does the // actual read while the the thread calling this method will blocks on the // std::future::get() std::future<std::size_t> future = ba::async_read(m_socket, buffer, ba::bind_executor(m_sessionStrand, ba::use_future)); try { // We block the calling thread here until we get the results of the async_read_some()... result = future.get(); } catch (boost::system::system_error &ex) // boost::system::system_error { auto exitCode = ex.code().value(); if ( exitCode == ba::error::eof ) { log ("Connection closed by the peer"); } } return results; // This is zero if eof occurs } The code sample above represents our issue. It was designed to support a 3rd-party library. The library expects a blocking call. The new code under development is using ASIO with a minimal number of network threads. The expectation is that this 3rd party library calls session::read using its dedicated thread and we adapt the call to an asynchronous call. The network call must be async since we are supporting many such calls from different libraries with minimal threads. What was unexpected and discovered late is that ASIO treats a connection closed as an error. Without the future, using a handler we could get the bytes transferred up to the point where the disconnect occurred. However, using a future, the exception is thrown and the bytes transferred becomes unknown. void handler (const boost::system::error_code& ec, std::size_t bytesTransferred ); Is there a way to do the above with a future and also get the bytes transferred? Or ss there an alternative approach where we can provide the library a blocking call by still use an asio::async_read or similar. Our expectation is that we could get the bytes transferred even if the client closed the connection. We're puzzled that when using a future this does not seem possible.
It's an implementation limitation of futures. Modern async_result<> specializations (that use the initiate member approach) can be used together with as_tuple, e.g.: ba::awaitable<std::tuple<boost::system::error_code, size_t>> a = ba::async_read(m_socket, buffer, ba::as_tuple(ba::use_awaitable)); Or, more typical: auto [ec, n] = co_await async_read(m_socket, buffer, ba::as_tuple(ba::use_awaitable)); However, the corresponding: auto future = ba::async_read(m_socket, buffer, ba::as_tuple(ba::use_future)); isn't currently supported. It arguably could, but you'd have to create your own completion token, or ask Asio devs to add support to use_future: https://github.com/chriskohlhoff/asio/issues Side-note: if you construct the m_socket from the m_sessioStrand executor, you do not need to bind_executor to the strand: using Executor = net::io_context::executor_type; struct Session { int32_t read(unsigned char* pBuffer, uint32_t bufferSizeToRead); net::io_context m_ioc; net::strand<Executor> m_sessionStrand{m_ioc.get_executor()}; tcp::socket m_socket{m_sessionStrand}; };
74,554,795
74,554,950
How do I pass a variable through Python using C++ in Python.h
I wanted to try out embedding Python into C++. I was able to get that to work but I wanted to start writing prints with variables which are in declared in c++. For example: (C++) int num = 43; PyRun_SimpleString("print("+num+")"); char g; std::cin>>g; PyRun_SimpleString("print("+g+")"); I tried to figure out how to use other related functions, but I don't seen to find enough information.
To pass char, Python script: def test(person): return "Hello " + person; C++: PyObject *pName, *pModule, *pFunc, *pArgs, *pValue; pName = PyUnicode_FromString((char*)"script"); pModule = PyImport_Import(pName); pFunc = PyObject_GetAttrString(pModule, (char*)"test"); pArgs = PyTuple_Pack(1, PyUnicode_FromString((char*)"User")); pValue = PyObject_CallObject(pFunc, pArgs); auto result = _PyUnicode_AsString(pValue); std::cout << result << std::endl; Output: Hello User To pass integer it's the same like above. Here you are passing over double 2.0. pArgs = PyTuple_Pack(1,PyFloat_FromDouble(2.0)); pValue = PyObject_CallObject(pFunc, pArgs); You can refer to all the apis here >> https://docs.python.org/3/c-api/
74,555,147
74,555,257
I need help in the variables in the Void
It doesn't accept my string and variables just in that part and I don't know why, I can't properly make my variables in the void part like matricula=_matricula because it doesn't detect it and says its undefined #include <iostream> using namespace std; class Alumnos{ private: string matricula; string nombre; int edad; string carrera; public: Alumnos(); void setAlumnos(string,string,int,string); string getAlumnoMatricula(); string getAlumnoNombre(); int getAlumnoEdad(); string getAlumnoCarrera(); }; Alumnos::Alumnos(){ } void Alumnos::setAlumnos(string_matricula,string_nombre,int_edad,string_carrera){ matricula=_matricula; nombre=_nombre; edad=_edad; carrera=_carrera; } ///////// string Alumnos::getAlumnoMatricula(){ return matricula; } string Alumnos::getAlumnoNombre(){ return nombre; } int Alumnos::getAlumnoEdad(){ return edad; } string Alumnos::getAlumnoCarrera(){ return carrera; } //////// string main(){ string alumnoMatricula,alumnoNombre,alumnoEdad,alumnoCarrera; Alumnos cl; cl.setAlumnos(A01643364,Sebastian,18,ITC); alumnoMatricula=cl.getAlumnoMatricula(); alumnoNombre=cl.getAlumnoNombre(); alumnoEdad=cl.getAlumnoEdad(); alumnoCarrera=cl.getAlumnoCarrera(); cout<<"La matricula del almuno es: "<<alumnoMatricula<<", su nombre es"<<alumnoNombre<<", su edad es"<<alumnoEdad<<"y su carrera es: "<<alumnoCarrera<<endl; }
You have missed spaces in the arguments (not string_matricula, it is string _matricula). Also while passing the arguments pass them as string inside " ". And main must return only int, it cannot return string. #include <iostream> using namespace std; class Alumnos{ private: string matricula; string nombre; int edad; string carrera; public: Alumnos(); void setAlumnos(string,string,int,string); string getAlumnoMatricula(); string getAlumnoNombre(); int getAlumnoEdad(); string getAlumnoCarrera(); }; Alumnos::Alumnos(){ } void Alumnos::setAlumnos(string _matricula,string _nombre,int _edad,string _carrera){ matricula=_matricula; nombre=_nombre; edad=_edad; carrera=_carrera; } ///////// string Alumnos::getAlumnoMatricula(){ return matricula; } string Alumnos::getAlumnoNombre(){ return nombre; } int Alumnos::getAlumnoEdad(){ return edad; } string Alumnos::getAlumnoCarrera(){ return carrera; } //////// int main(){ string alumnoMatricula,alumnoNombre,alumnoEdad,alumnoCarrera; Alumnos cl; cl.setAlumnos("A01643364","Sebastian",18,"ITC"); alumnoMatricula=cl.getAlumnoMatricula(); alumnoNombre=cl.getAlumnoNombre(); alumnoEdad=cl.getAlumnoEdad(); alumnoCarrera=cl.getAlumnoCarrera(); cout<<"La matricula del almuno es: "<<alumnoMatricula<<", su nombre es"<<alumnoNombre<<", su edad es"<<alumnoEdad<<"y su carrera es: "<<alumnoCarrera<<endl; }
74,555,448
74,568,133
How to include external library in C++ from GitHub using CLion and CMake on Windows?
I have an assignment to create a C++ program, and one of the libraries we are encouraged to use is GLM, found on this GitHub link here: https://github.com/g-truc/glm. I've been trying to figure out how to include this library in my program but I can't make heads or tails of the process. I am new to C++ and CMake, and everything I find when looking it up is either tailored to other OSes or platforms (I'm using Windows 10), or I don't yet understand it. I'd appreciate some help in clarifying the steps I need to take. Right now, all I have is a simple Hello World main file, and a CMakeLists.txt file auto-generated by CLion. My goal is to be able to write something like "#include <mat4x4.hpp>", and access the methods in the library. Here are some questions I've been running into: Do I need to download this library from GitHub manually in order to use it? (I'm assuming yes, since there doesn't seem to be a package manager) If so, do I need to copy all or parts of it into my program structure? Do I need to separately compile it and add the compiled file into my program structure? When adding external libraries, do I need to sort things into "lib", "include", and "src" folders? Do I need to mark these directories as library, source, or otherwise? CLion already has a little "External Libraries" directory. Do I place things there? (The subfolders in the image were added by CLion) Once I get everything into place, how should my CMakeLists.txt file look to be able to link these libraries correctly? So as you can see, being so new to this I can't really identify yet what the overarching process looks like. Here's what my first attempt looked like: (here, I had downloaded the library as a .zip, uncompressed it and copied the whole thing into a lib folder) It seems CMake was able to find GLM, since it printed a version number. But it still won't find the library when writing the "#include" line, so I must be missing a step somewhere. Any and all help is greatly appreciated. If you need any more information from me, just ask!
With the help of a friend, I managed to solve it! For posterity, here's the setup that worked for me. I downloaded the library from GitHub using the releases page on the right sidebar: I extracted the downloaded .zip, and placed the entire resulting folder in my project structure. For that, I made a "lib" folder (though I suspect folder names or structure isn't as important as I first thought). This is my working project structure: As you can see, I also no longer have a separate "src" folder, though I'm sure I could add one if need be. The important part here is that each folder level has its own CMakeLists.txt. In short, the CMakeLists in the project root links the "lib" folder, and the CMakeLists in the lib folder links the "glm" folder. And the one in the glm folder was in the library I downloaded, and it already handles all the linking for subsequent folders and files. Here's what the CMakeLists in the project root looks like: Line 7 links the lib folder. Line 8 creates an executable from the source files I've created (main.cpp, set on line 5). And line 9 links the glm library and my executable. Here's what the CMakeLists in the lib folder looks like: Not much in there but linking the glm subdirectory, which then already has a library named glm that I can use in the root CMakeLists. With all that set up, I can now successfully use the "#include" command in my main.cpp, and it finds the library: Hopefully any other libraries I add can follow the same process. If anyone else runs into the same roadblock, I hope this helps clarify things.
74,555,610
74,556,160
What does the parameter assigned to an unordered_map<> name hold?
I was going through a great article on LZW compression algorithm by Mark Nelson, and found something in the code I haven't yet encountered. In the code, he used unordered_map to store strings and their corresponding frequency. The declaration of the map was: std::unordered_map<std::string, unsigned int> codes( (max_code * 11)/10 ); max_code stores the maximum number of entries in the map, i.e. 32767. The code: void compress( INPUT &input, OUTPUT &output, const unsigned int max_code = 32767 ) { //code } I am unaware as to what parameter does an unsigned int value associated with codes hold. Also, could someone enlighten me as to why the max_code value is multiplied by 11 and then divided by 10? Here is the compress function for reference: template<class INPUT, class OUTPUT> void compress( INPUT &input, OUTPUT &output, const unsigned int max_code = 32767 ) { input_symbol_stream<INPUT> in( input ); output_code_stream<OUTPUT> out( output, max_code ); std::unordered_map<std::string, unsigned int> codes( (max_code * 11)/10 ); for ( unsigned int i = 0 ; i < 256 ; i++ ) codes[std::string(1,i)] = i; unsigned int next_code = 257; std::string current_string; char c; while ( in >> c ) { current_string = current_string + c; if ( codes.find(current_string) == codes.end() ) { if ( next_code <= max_code ) codes[ current_string ] = next_code++; current_string.erase(current_string.size()-1); out << codes[current_string]; current_string = c; } } if ( current_string.size() ) out << codes[current_string]; }
The std::unordered_map type template has a number of constructors that accept a size_type; typically std::size_t, which is an unsigned integer. This value is related to the semantics, or rather the typical implementation, of an unordered map as a hash-set. From the link above: explicit unordered_map(size_type bucket_count, const Hash& hash = Hash(), const key_equal& equal = key_equal(), const Allocator& alloc = Allocator() ); Constructs empty container. Sets max_load_factor() to 1.0. For the default constructor, the number of buckets is implementation-defined. ... bucket_count - minimal number of buckets to use on initialization. If it is not specified, implementation-defined default value is used It serves as an indicator of how much data you expect the container to hold. This of course will not be perfect because of hash collisions. But it serves as a hint for the container for how much memory to allocate, similar to what std::vector::reserve() would do. My guess is that by choosing slightly more than you actually need, here 1.1 as much, you are more likely to avoid reallocations on the bucket-level. 1.1 sounds a bit too conservative to me, I might have gone for 1.5 or higher. But possibly experiments were made to determine what safety-factor to use.
74,555,908
74,555,942
Scope of variables in Qt vs vanilla c++
Disclaimer: I am total newbie to Qt. Let's assume we have a byte array returned from a function innerFunc that is later used in another function outerFunc. QByteArray innerFunc(){ QProcess ls; ls.start("ls", QStringList() << "-1"); return ls.readAll(); } void outerFunc(){ QByteArray gotcha = innerFunc(); . . . } In vanilla c++ I would expect readAll function to return a pointer that needs to be deleted later. In Qt this function returns an instance of the QByteArray class so I guess it shouldn't be accessed outside of the innerFunc's scope. If so, how should I properly transfer the data to an outer function? Should it copied to QByteArray *tmp = new QByteArray or is it unnecessary?
The code you have looks fine. QByteArray is like std::vector<uint8_t> or std::string and not like a pointer. It manages its own memory. It's fine to return it from a function or pass it to a function by value. The compiler will take care of copying and/or moving the data from one object to another as appropriate, using the contructors/operators defined by the QByteArray class. QByteArray header file QByteArray documentation
74,556,155
74,556,257
Is Q_PROPERTY a function-like macro in C++?
In my opinion,the using of a function-like macro in C++ is similar to the using of a common function. It seems to be like this: macroFunctionName(arg1, arg2, arg3); However, the using of Q_PROPERTY usually looks like this: Q_PROPERTY(Qt::WindowModality windowModality READ windowModality WRITE setWindowModality) As we can see, they are different.There is no comma in the using of Q_PROPERTY.I have never seen a function-like macro which was used like Q_PROPERTY.I am even not sure whether Q_PROPERTY is a function-like macro in C++.So is it ill-formed in C++? Or it's just a special syntax for MOC in Qt? I tried to find it in the C++ standard document but nothing about it was found.
I looked in Qt's ./src/corelib/kernel/qobjectdefs.h file for the definition, and it looks like this: #define Q_PROPERTY(...) QT_ANNOTATE_CLASS(qt_property, __VA_ARGS__) ... which would make Q_PROPERTY a variadic macro. Of course all it does is expand out to QT_ANNOTATE_CLASS, which is a different macro, one that Qt's moc utility presumably knows how to handle in a meaningful way when generating its moc_*.cpp files. As for the use of spaces rather than commas; you're right, the preprocessor doesn't treat spaces as argument-separators. I suspect that the C++ preprocessor is simply passing the entire line (i.e. "Qt::WindowModality windowModality READ windowModality WRITE setWindowModality") into the QT_ANNOTATE_CLASS macro as a single argument, and that moc's QT_ANNOTATE_CLASS macro-definition is doing some stringification preprocessor tricks in order to parse it as a string-argument.
74,556,481
74,556,567
C++ template placeholders not permitted in function arguments
In the following C++ code, a template placeholder in argument of function fun1, and in the return type of function ret1, does not compile: template <typename T = int> class type { T data; }; void fun1(type arg); // Error: template placeholder not permitted in this context void fun2(type<> arg); // Ok void fun3(type<int> arg); // Ok type ret1(); // Error: Deduced class type 'type' in function return type type<> ret2(); // Ok type<int> ret3(); // Ok int main() { type var1; // Ok!!!!!! type<> var2; // Ok type<int> var3; // Ok } But, var1 is ok. Why does var1 compile, but fun1 and ret1 do not? Is there any logic behind this inconsistent behavior between function declarations and variable declarations?
var1 benefits from CTAD, where all non-defaulted template arguments (i.e. none) can be deduced from the initialisation. Both function declarations however, are not candidates for CTAD, so the template argument list must be supplied even if that list is empty. Deduction for class templates Implicitly-generated deduction guides When, in a function-style cast or in a variable's declaration, the type specifier consists solely of the name of a primary class template C (i.e., there is no accompanying template argument list), candidates for deduction are formed as follows: ... (emphasis added)
74,556,894
74,556,923
Populating protobuf fields in C++
In a codebase I see some protobuf definition as message Foo { repeated FooData foo_data = 1; } Later on these protobufs are used in a C++ method in the following way auto& bar = *protobuf_foo.add_foo_data(); but I don't see add_foo_data() defined anywhere. Is this a protobuf property that prepending add_ and adding parentheses at the end is some sort of reserved syntax?
This method comes from c++ code generated from protobuf definitions. https://developers.google.com/protocol-buffers/docs/reference/cpp-generated
74,556,971
74,556,996
class member values doesn't get changed by function... "noob question"
I am trying to update the particles positions by calling a function for the class.. The values for v_x, v_y, a_x, a_y doesnt keep its new value after the function. I thought this would work because update_pos is a member function of the class. what am i doing wrong here? class particle : public sf::CircleShape { float mass; float v_x, v_y, a_x, a_y; public: particle(float radius,int x, int y) { setRadius(radius); setOrigin(radius, radius); setPosition(x, y); setFillColor(sf::Color::White); mass = radius; v_x = 0; v_y = 0; a_x = 0; a_y = 0; }; void update_pos() { float g = 9; //upd acc a_x += g * 0 / mass; a_y += g / mass; //upd vel v_x += a_x; v_y += a_y; //move particle setPosition(getPosition().x + v_x, getPosition().y + v_y); } }; this function is used in main to update every particle. void update_particles(std::vector<particle>& particles) { for (particle p : particles) { p.update_pos(); } }
This code for (particle p : particles) copies every particle in your vector, p is a copy. So you are changing copies of the particles in your vector, not the originals. To avoid the copy you need a reference for (particle& p : particles) For a largish class like particle a reference is desirable anyway, just for efficiency reasons.
74,557,018
74,582,963
Why does nvmlDeviceGetTemperature only work in debug mode?
Using VS2022 the following code snippet works in debug mode but not in release mode: nvmlInit(); nvmlDevice_t devH; auto ret = nvmlDeviceGetHandleByIndex_v2(0, &devH); if (ret != NVML_SUCCESS) DPrint("ERROR!"); u32 tt{}; ret = nvmlDeviceGetTemperature(devH, NVML_TEMPERATURE_GPU, &tt); if (ret != NVML_SUCCESS) DPrint("%s\n\n", nvmlErrorString(ret)); DPrint("TEMP: %u\n", tt); Sleep(10000); In release mode I get NOT SUPPORTED but in debug mode it works fine, printing the temperature. I have checked all the properties especially the linker ones and I cannot find any significant differences that would explain it. DPrint is a simple utility to print to the output window.
Turns out the release build was loading a different version of nvml.dll. Fixed it and now it works!
74,558,080
74,558,156
call an immediate parent in c++
This is a true story of evolving code. We began with many classes based on this structure: class Base { public: virtual void doSomething() {} }; class Derived : public Base { public: void doSomething() override { Base::doSomething(); // Do the basics // Do other derived things } }; At one point, we needed a class in between Base and Derived: class Base; class Between : public Base; class Derived : public Between; To keep the structure, Between::doSomething() first calls Base. However now Derived::doSomething() must be changed to call Between::doSomething()... And this goes for all methods of Derived, requiring search & replace to many many calls. A best solution would be to have some this->std::direct_parent mechanism to avoid all the replacements and to allow easy managing of class topology. Of course, this should compile only when there's a single immediate parent. Is there any way to accomplish this? If not, could this be a feature request for the C++ committee?
What I can suggest is parent typedef in Derived: class Base { public: virtual void doSomething() {} }; class Derived : public Base { private: typedef Base parent; public: void doSomething() override { parent::doSomething(); // Do the basics // Do other derived things } }; Then after introduction of Between the only change needed in Derived is the change of the parent typedef: class Derived : public Between { private: typedef Between parent; public: void doSomething() override { parent::doSomething(); // Do the basics // Do other derived things } };
74,558,405
74,597,755
Creating c++ library using cmake
Dear cmake / c++ experts, I created a small library for display and input on the console. Now I would like to use it in another project. Unfortunately, even after quite some time spent in the cmake documents, I cannot get it to work. The library is here: https://github.com/HEIGVD-PRG1-F-2022/prg1f-io and uses the following CMakeLists.txt: cmake_minimum_required(VERSION 3.23) project(prg1f-io VERSION 0.1 DESCRIPTION "Input and display methods for PRG1-F") set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") add_library(prg1f-io STATIC src/display.cpp) set_target_properties(prg1f-io PROPERTIES VERSION ${PROJECT_VERSION}) set_target_properties(prg1f-io PROPERTIES PUBLIC_HEADER include/display.h) include(GNUInstallDirs) install(TARGETS prg1f-io LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) And I created a small test here: https://github.com/HEIGVD-PRG1-F-2022/prg1f-test with the following CMakeLists.txt: cmake_minimum_required(VERSION 3.23) project(prg1f_test) set(CMAKE_CXX_STANDARD 20) include(FetchContent) FetchContent_Declare(prg1f-io GIT_REPOSITORY https://github.com/HEIGVD-PRG1-F-2022/prg1f-io.git GIT_TAG main ) FetchContent_MakeAvailable(prg1f-io) add_executable(prg1f-test main.cpp) target_link_libraries(prg1f-test PRIVATE prg1f-io) While the CMakeLists.txt in the test does download the library and compiles it, I cannot get access to the header files in the test. I tried different includes, but none of the following work: #include <prg1f-io/include/display.h> #include <prg1f-io/display.h> #include <prg1f-io> #include <display.h> I'm sure it's a little line somewhere in one of the CMakeLists.txt, but I cannot find it. Any help is greatly appreciated!
Thanks to @Tsyvarev, I can now rest in peace: The CMakeLists.txt of the library: cmake_minimum_required(VERSION 3.23) project(prg1f-io VERSION 0.1 DESCRIPTION "Input and display methods for PRG1-F") set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") add_library(prg1f-io STATIC src/display.cpp) set_target_properties(prg1f-io PROPERTIES VERSION ${PROJECT_VERSION}) target_include_directories(prg1f-io PUBLIC include) And the CMakeLists.txt of the binary using the library: cmake_minimum_required(VERSION 3.23) project(prg1f_test) set(CMAKE_CXX_STANDARD 20) include(FetchContent) FetchContent_Declare(prg1f-io GIT_REPOSITORY https://github.com/HEIGVD-PRG1-F-2022/prg1f-io.git GIT_TAG main ) FetchContent_MakeAvailable(prg1f-io) add_executable(prg1f-test main.cpp) target_link_libraries(prg1f-test PRIVATE prg1f-io) Now I can include the headers using: #include <display.h> All I'm missing now is how to #include<prg1f-io/display.h> without having to add a prg1f-io/include/prg1f-io/display.h directory.
74,558,965
74,559,285
How to make begin and end functions rvalue qualified
I am writing a file parser. Since the user can pass through the file only once I want the iterator to be accessible only from rvalue reference. MyParser parser("/path/to/file"); for(auto it : std::move(parser)){ // example for(auto & [key, value]: it){ std::court << key << '\t' << value << std::endl; } } So, I did the following class MyParser{ public: MaParser(const std::string &path): begin_iterator_(path){} // ====== Begin iterator class ============== class iterator{ public: typedef std::map<std::string, std::string> value_type; // Ctor iterator(const std::string & path):{ // Initialize } // Default ctor iterator() = default; // Move ctor iterator(iterator && other){ istream_ = std::move(other.istream_); values_ = std::move(other.value_); } iterator & operator=(iterator && other){ istream_ = std::move(other.istream_); values_ = std::move(other.value_); return *this; } void operator++(){// definition} value_type & operator*(){ return value_; } bool operator==(const iterator & other) const { return false; // logic here } bool operator!=(const iterator & other) const { return !(*this == other); } private: std::unique_ptr<std::istream> istream_; value_type value_; }; // ====== End iterator class ============== iterator && begin() &&{ return std::move(begin_iterator_); } iterator && end() && { return iterator(); } private: iterator begin_iterator_; }; Now, I can iterate like this: for(auto it = std::move(parser).begin(); it != myParser::iterator(); ++it){ } but when I try to iterate according to the original intention I get an error cannot convert 'this' pointer from 'MyParser' to 'MyParser &&'. Q1: How do I solve this problem? Q2: If instead of the begin_iterator in the function begin do iterator && begin() &&{ return iterator(path_); // Assuming we stored the path in a local variable. } the program crashes on the iterator init auto it = std::move(parser).begin(); , when trying to move value_ in the move-constructor. Why?
A range-based for is basically syntax sugar. Your loop of: for (auto it : std::move(parser)) { statements; } is equivalent to: { auto && __range = std::move(parser); for (auto __begin = __range.begin(), end = __range.end(); __begin != __end; ++__begin) { auto it = *__begin; { statements; } } } So even though __range is an rvalue reference, __range.begin() still calls begin on an lvalue (the rvalue-ness isn't used). There's no way around this, you cannot make it so that only rvalues can be iterated over in a range-for. For reference, std::ranges::istream_view does a similar thing and the only thing it does for safety is make its iterator move-only, so what you already have should be enough. For your second question, if you return a temporary from iterator && begin() &&, the temporary is destroyed before the function returns and you get a dangling reference. Your current end function suffers from the same problem. Simply return by value iterator begin() &&. The move from the temporary should be elided.
74,560,021
74,560,150
Should I precautionary move callables (e.g. lambdas?)
I have this striped-down example of a timer that I'd like to be instantiable with any kind of callable. Is it advisable to precautionary move the callable into a data member for efficiency? #include <concepts> #include <cstdio> #include <string> #include <utility> template <std::invocable Cb> class timer { public: timer(Cb cb) : cb_ { std::move(cb) } { } auto call() { cb_(); } private: Cb cb_; }; int main() { std::string something_to_print = "Hello World!\n"; timer some_timer([&]() { printf(something_to_print.c_str()); }); some_timer.call(); return 0; } I can't see any difference in the assembly if I move or copy the lambda. Does it ever make a difference?
Your lambda has only reference captures. Moving an lvalue-reference does exactly the same as copying it. If you had [=] captures, the move would actually do something. The answer to whether or not to do this in general is: "it depends on the situation." W.r.t. performance: measure.
74,561,478
74,561,612
Why doesn't "Guaranteed Copy Elision" mean that push_back({arg1, arg2}) is the same as emplace_back(arg1, arg2)?
Firstly, I've heard that Guaranteed Copy Elision is a misnomer (as, I currently understand, it's more about fundamentally redefining the fundamental value categories, r/l-values to l/x/pr-values, which fundamentally changes the meaning and requirements of a copy), but as that's what it's commonly referred as, I will too. After reading a bit on this topic, I thought I finally understood it - at least well enough to think that: my_vector.push_back({arg1, arg2}); is, as of c++17, equivalent to: my_vector.emplace_back(arg1, arg2); I recently tried to convince my colleague of this. The only problem was he showed me that I was completely wrong! He wrote some godbolt code (like this) where the assembly shows that the push_back creates a temporary that gets moved into the vector. So, to complete my question I must first justify that there's some reason for confusion here. I'll quote the well-regarded stackoverflow answer on this topic (emphasis mine): Guaranteed copy elision redefines the meaning of a prvalue expression. [...] a prvalue expression is merely something which can materialize a temporary, but it isn't a temporary yet. If you use a prvalue to initialize an object of the prvalue's type, then no temporary is materialized. [...] The thing to understand is that, since the return value is a prvalue, it is not an object yet. It is merely an initializer for an object [...] In my case I would've thought that auto il = {arg1, arg2} would call the constructor for std::initializer_list, but that {arg1, arg2} in push_back({arg1, arg2}) would be a prvalue (as it's unnamed) and so would be an initiliser for the vector element without being initialised itself. When you do T t = Func();, the prvalue of the return value directly initializes the object t; there is no "create a temporary and copy/move" stage. Since Func()'s return value is a prvalue equivalent to T(), t is directly initialized by T(), exactly as if you had done T t = T(). If a prvalue is used in any other way, the prvalue will materialize a temporary object, which will be used in that expression (or discarded if there is no expression). So if you did const T &rt = Func();, the prvalue would materialize a temporary (using T() as the initializer), whose reference would be stored in rt, along with the usual temporary lifetime extension stuff. Guaranteed elision also works with direct initialization Could someone kindly explain to me why Guaranteed Copy Elision doesn't apply to my example the way that I expected?
but that {arg1, arg2} in push_back({arg1, arg2}) would be a prvalue (as it's unnamed) and so would be an initiliser for the vector object without being initialised itself. I assume that with "vector object" you mean here the vector element, the object that will be stored in the storage managed by the vector and which the push_back/emplace_back is supposed to add to the it. {arg1, arg2} itself is not an expression, it is just a braced-init-list, a different grammatical construct. So it itself doesn't have a value category. However it has rules as to how it acts in overload resolution and how it initializes objects and references. The overload chosen for push_back will be void push_back(value_type&&); where value_type is the element type of the vector. The reference parameter in this overload needs to reference some object of type value_type. So the braced-init-list must be used to construct an (temporary) object of type value_type to bind this reference to. However this can't be the object that is stored in the vector, because it is a temporary created in the context of the caller. The caller doesn't know where push_back will construct the actual element for the vector. Hence push_back will need to do a move construction from the temporary object bound to the parameter reference to the actual object placed in the vector's storage. So effectively my_vector.push_back({arg1, arg2}); is the same as my_vector.push_back(value_type{arg1, arg2});, only that value_type{arg1, arg2} is an actual prvalue expression which will be materialized to a temporary object when initializing push_back's reference parameter from it. Because of this almost identical behavior one might sloppily say that {arg1, arg2} "is a prvalue" or "is a temporary", even though that is technically not correct. push_back doesn't have any overload that doesn't take a reference to a value_type, so this is always unavoidably with it. emplace_back on the other hand takes any types as arguments and then just forwards them directly to the construction of the object stored in the vector's storage. It is also impossible to forward braced-init-lists. There is no syntax to capture them while preserving the type of the individual list elements. You can only initialize an object of a specified type from the whole list as with push_back or initialize an array or std::initializer_list with homogeneous element type (one element from each list element), which is what an initializer-list constructor would do (with the homogeneous type being the vector's element type).
74,562,129
74,562,340
VSCode Debugger not Launching
I am writing a C++ program in VSCode. However, when I press F5, all it does is build the project. I tried making another simple project in VSCode to see if it works, but no luck. Here is my mini-program launch.json { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "C/C++: clang++ build and debug active file", "type": "cppdbg", "request": "launch", "program": "${fileDirname}/${fileBasenameNoExtension}", "args": [], "stopAtEntry": true, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "lldb", "preLaunchTask": "C/C++: clang++ build active file" } ] } tasks.json { "tasks": [ { "type": "cppbuild", "label": "C/C++: clang++ build active file", "command": "/usr/bin/clang++", "args": [ "-fcolor-diagnostics", "-fansi-escape-codes", "-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ], "version": "2.0.0" } main.cpp #include <iostream> int main() { int sum = 0; for (int i = 0; i < 100; i++) { sum += i; std::cout<<"Sum: " << sum << std::endl; } return 0; } I have tried reinstalling VSCode with no luck. When I try to debug a python script, it works just fine, so the problem is only with C++. How do I debug this debugging error? CLARIFICATION: I am not getting an error from the debugger. Instead, the debugger for C++ isn't launching at all.
Instead, the debugger for C++ isn't launching at all. Because you are missing the debugger's path in your launch.json. Add a path to the debugger within the miDebuggerPath. { "version": "0.2.0", "configurations": [ { "name": "C/C++: clang++ build and debug active file", . . "miDebuggerPath": "/path/to/gdb" } ] } Or, you can use the Add Configuration button (visible in launch.json) to set up a new debugging configuration.
74,564,118
74,567,981
prevent initializing std::optional<std::reference_wrapper<const T>> with rvalue std::optional<T>
std::reference_wrapper cannot be bound to rvalue reference to prevent dangling pointer. However, with combination of std::optional, it seems that rvalue could be bound. That is, std::is_constructible_v<std::reference_wrapper<const int>, int&&>) is false but std::is_constructible_v<std::optional<std::reference_wrapper<const int>>, std::optional<int>&&> is true. Here's an example: #include <iostream> #include <optional> auto make() -> std::optional<int> { return 3; } int main() { std::optional<std::reference_wrapper<const int>> opt = make(); if (opt) std::cout << opt->get() << std::endl; return 0; } I expected this code will be rejected by compiler, but it compiles well and opt contains dangling pointer. Is this a bug of standard library? Or, is it just not possible to prevent dangling pointer here because of some kind of limitaion of C++ language specification? If it is a bug of standard library, how can I fix it when I implement my own optional type? It it's a limitation of current C++ specification, could you tell me where this problem comes from?
@Jarod42 already pointed out the core reason why this code compiles, but I will elaborate a bit. The following two constructor templates for std::optional<T> are relevant to this question: template <class U> constexpr optional(const optional<U>& other) requires std::is_constructible_v<T, const U&>; // 1 template <class U> constexpr optional(optional<U>&& other); requires std::is_constructible_v<T, U>; // 2 Note that the requires-clauses above are for exposition only. They might not be present in the actual declarations provided by the library implementation. However, the standard requires constructor templates 1 and 2 to only participate in overload resolution when the corresponding std::is_constructible_v constraint is satisfied. The second overload will not participate in overload resolution because std::reference_wrapper<const int> is not constructible from int (meaning an rvalue of type int), which is the feature that is intended to prevent dangling references. However, the first overload will participate, because std::reference_wrapper<const int> is constructible from const int& (meaning an lvalue of type const int). The problem is that, when U is deduced and the std::optional<int> rvalue is bound to the const optional<U>& constructor argument, its rvalueness is "forgotten" in the process. How might this issue be avoided in a user-defined optional template? I think it's possible, but difficult. The basic idea is that you would want a constructor of the form template <class V> constexpr optional(V&& other) requires (is_derived_from_optional_v<std::remove_cvref_t<V>> && see_below) // 3 where the trait is_derived_from_optional detects whether the argument type is a specialization of optional or has an unambiguous base class that is a specialization of optional. Then, If V is an lvalue reference, constructor 3 has the additional constraint that the constraints of constructor 1 above must be satisfied (where U is the element type of the optional). If V is not a reference (i.e., the argument is an rvalue), then constructor 3 has the additional constraint that the constraints of constructor 2 above must be satisfied, where the argument is const_cast<std::remove_cv_t<V>&&>(other). Assuming the constraints of constructor 3 are satisfied, it delegates to constructor 1 or 2 depending on the result of overload resolution. (In general, if the argument is a const rvalue, then constructor 1 will have to be used since you can't move from a const rvalue. However, the constraint above will prevent this from occurring in the dangling reference_wrapper case.) Constructors 1 and 2 would need to be made private and have a parameter with a private tag type, so they wouldn't participate in overload resolution from the user's point of view. And constructor 3 might also need a bunch of additional constraints so that its overload resolution priority relative to the other constructors (not shown) is not higher than that of constructors 1 and 2. Like I said, it's not a simple fix.
74,564,251
74,599,531
How to build an osx universal binary with different code for intel and arm architecture
My goal is to create a universal/fat binary of my app, my understanding is that means xcode will create an intel/x86_64 build and an M1/arm build and package them together. My code uses intel intrinsics which I can replace with NEON in the arm build but to do so I need a way to create a conditional block at compile time for the target architecture. Is this possible? How can I achieve this? What I've tried so far: #include "TargetConditionals.h" #if defined TARGET_CPU_ARM64 #include <sse2neon.h> //NEON intristics #endif #if defined TARGET_CPU_X86_64 #include <emmintrin.h> //Intel intristics #endif When this was used Xcode tried to compile the arm code into the x86_64 build which failed. I suppose both targets are defined at compile time but Xcode builds intel then arm objects separately so there must be a way for it to define which is which that I can use.
I found the solution, with help from the comments (thank you!) I was misusing the definitions, all these are defined in the header but only the relevant ones are set to 1, changing my "#ifdef x" to "#if x == 1" was the solution. #if (TARGET_CPU_ARM64 == 1) #include <sse2neon.h> #elif (TARGET_CPU_X86_64 == 1) #include <emmintrin.h> #endif
74,564,331
74,569,538
CGAL: read off file results in 0 vertices and 0 faces
Problem Here's a simple CGAL .off read application. I was trying to read ModelNet40/airplane/train/airplane_0001.off and ModelNet40/airplane/train/airplane_0002.off respectively, but ModelNet40/airplane/train/airplane_0002.off gives a surface_mesh with 0 vertices and 0 faces. Those two off file are from ModelNet40 without any modifications. # console output for airplane_0001.off Initial Vertices: 90714 Initial Edges: 193500 # console output for airplane_0002.off Initial Vertices: 0 Initial Edges: 0 Problem CGAL code decimation.cpp #include <CGAL/Simple_cartesian.h> #include <CGAL/Surface_mesh.h> // Simplification function #include <CGAL/Surface_mesh_simplification/edge_collapse.h> // Visitor base #include <CGAL/Surface_mesh_simplification/Edge_collapse_visitor_base.h> // Stop-condition policy #include <CGAL/Surface_mesh_simplification/Policies/Edge_collapse/Count_ratio_stop_predicate.h> #include <iostream> #include <fstream> typedef CGAL::Simple_cartesian<double> Kernel; typedef Kernel::Point_3 Point_3; typedef CGAL::Surface_mesh<Point_3> Surface_mesh; typedef boost::graph_traits<Surface_mesh>::halfedge_descriptor halfedge_descriptor; typedef boost::graph_traits<Surface_mesh>::vertex_descriptor vertex_descriptor; namespace SMS = CGAL::Surface_mesh_simplification; typedef SMS::Edge_profile<Surface_mesh> Profile; int main(int argc, char ** argv) { Surface_mesh surface_mesh; const std::string filename = CGAL::data_file_path(argv[1]); std::cout << filename << std::endl; std::ifstream is(filename); if(!is || !(is >> surface_mesh)) { std::cerr << "Failed to read input mesh: " << filename << std::endl; return EXIT_FAILURE; } if(!CGAL::is_triangle_mesh(surface_mesh)) { std::cerr << "Input geometry is not triangulated." << std::endl; return EXIT_FAILURE; } std::cout << "Initial Vertices: " << surface_mesh.number_of_vertices() << std::endl << "Initial Edges: " << surface_mesh.number_of_edges() << std::endl; return EXIT_SUCCESS; } CMakeLists.txt project(modelnet40) cmake_minimum_required(VERSION 3.23.0) set(CMAKE_BUILD_TYPE Release) find_package(CGAL REQUIRED OPTIONAL_COMPONENTS Qt5) find_package(Qt5 COMPONENTS Widgets REQUIRED) find_package(OpenGL) include_directories(${OPENGL_INCLUDE_DIR}) add_executable(modelnet40 decimation.cpp) set(CMAKE_CXX_FLAGS "-DCGAL_USE_BASIC_VIEWER") target_link_libraries(modelnet40 CGAL::CGAL CGAL::CGAL_Basic_viewer) Tested in python import open3d as o3d path = "ModelNet40/airplane/train/airplane_0002.off" mesh = o3d.io.read_triangle_mesh(path) print(mesh) I tested both files using open3d.io.read_triangle_mesh(path) in python and both of them are ok, but it gives 0 vertices and 0 faces in CGAL. Result in python # console for airplane_0001.off TriangleMesh with 90714 points and 104773 triangles. # console for airplane_0002.off TriangleMesh with 94335 points and 118614 triangles.
You cannot just use operator>>() because your mesh has isolated vertices and non-manifold edges. You must instead read a polygon soup, orient the triangles and if necessary duplicate edges so that you obtain a 2-manifold, potentially wirh border edges. Have a look at this example in the User Manual. Or use directly read_polygon_mesh()
74,564,381
74,564,604
Using `std::experimental::propagate_const` for arrays
The question is simple: why can't I use propagate_const for arrays? The following line gives errors: std::experimental::propagate_const<std::unique_ptr<int[]>> ptr = std::make_unique<int[]>(1); The errors (gcc version 13.0): /usr/local/include/c++/13.0.0/experimental/propagate_const: In Instanziierung von »struct std::experimental::fundamentals_v2::__propagate_const_conversions<std::unique_ptr<int []> >«: /usr/local/include/c++/13.0.0/experimental/propagate_const:108:11: erfordert durch »class std::experimental::fundamentals_v2::propagate_const<std::unique_ptr<int []> >« ../../livews2223/l00/main.cpp:182:64: von hier erfordert /usr/local/include/c++/13.0.0/experimental/propagate_const:55:37: Fehler: no match for »operator*« (operand type is »std::unique_ptr<int []>«) 55 | = remove_reference_t<decltype(*std::declval<_Tp&>())>; | ^~~~~~~~~~~~~~~~~~~~~ The the goal is to prevent that a const element-function can change array elements like: struct A { void foo() const { a[0] = 2; // should not be possible } // std::experimental::propagate_const<std::unique_ptr<int[]>> a = std::make_unique<int[]>(2); std::unique_ptr<int[]> a = std::make_unique<int[]>(2); };
unique_ptr<T[]> is neither a pointer nor a pointer-like type. It's an array-like type. That's why it has operator[] but not operator*. It makes little sense to use *ptr on an array (for language arrays, this accesses the first element, but using ptr[0] makes it much more clear what's going on). So unique_ptr<T[]> provides no such operator. And therefore, it isn't pointer-like enough for propagate_const to work.
74,564,401
74,564,559
Is it possible to define a constructor taking a universal reference with defaulted value?
When I try to define a constructor taking a universal reference with a defaulted value as a parameter like this: struct S { int x; // I know that universal ref is useless for int, but it's here for simplicity template<class T> S(const T&& arg = 123) : x(std::forward(arg)) { } // S(const auto&& arg = 123) : x(std::forward(arg)) { } // The auto-syntax fails as well, yields similar error }; int main() { S s; } I get an error: <source>:18:7: error: no matching constructor for initialization of 'S' S s; ^ <source>:10:5: note: candidate template ignored: couldn't infer template argument 'T' S(const T&& arg = 123) : x(std::forward(arg)) { } ^ <source>:3:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided struct S { ^ <source>:3:8: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 0 were provided Is there a way to do it with a universal reference or do I have to do it in a different way?
You still need to specify a default argument for the template parameter. It will not be deduced from the function parameter's default argument: template<class T = int> You also are misusing std::forward. It always requires a type template argument that should be the template parameter used in the forwarding reference named by the argument. x(std::forward<T>(arg)) And finally, a const rvalue reference almost never makes sense. In particular it doesn't form a forwarding reference. Remove the const: S(T&& arg = 123) Then it should compile. But just declaring an additional overload without parameters might be simpler. Note: In the above forwarding reference is synonymous with what the question refers to as universal reference. The former is the now technically correct term used in the standard. The latter is older and was popularized in writing before there was an official term.
74,565,192
74,605,440
Recommended way of wrapping a third party library c function with void* arguments in c++?
I have a third party closed source c library that interfaces with hardware. The library has some api functions that accept void * arguments to read/write and configure some io, like so: int iocall(int cmd, void * args); int iorw(int cmd, void * buff, size_t buff_size); I want to wrap these in a c++ class to be able to inject that class, be able to mock it using gtest and introduce exceptions and get rid of all the return value checks inside the upper service classes. So far so good. Here comes my question: What would be the best way of designing an interface for that class when it comes to the void * arguments? interface.h class wrap: { virtual void wrap_iocall(int cmd, ??) = 0; } interface_impl.h class wrap: { void wrap_iocall(int cmd, ??) override { int ret{iocall(cmd, ??)}; // do some more stuff, e.g. exceptions and so on } } My first take was to just overload the calls with dedicated types - but since there are a lot of them, this might be a pain to maintain and I will need to change the interface when another call is needed (e.g. other hardware call) + the library might get updates which forces me to update types. The second thing I thought about is using std::any which would fit my use case but I am unsure how I would pass a pointer to the std::any container to the underlying c-function? I thought about pushing it into a std::vector<std::any> and use the .data() function to pass a pointer, but then I am left with a guess on the size of that container I think? And this sounds like a very bad attempt to achieve what I am looking for. The third thing I came across was a solution using templates, but if my understanding is correct, these things cannot be virtual and hence break with my intention to mock the interface, requiring it to be virtual. So I think this might not work either. The last thing I can currently think of is sticking to just void * in the wrapping function and have the upper service layer handle the type casts, e.g. allocate the struct for the specific device call and pass the pointer to the void * argument of the wrapper. This is by far my least favorite option. I want to stick to the principle of type safe function arguments but I am not sure of how to proceed from here. Any help/feedback is appreciated!
Thank you all for your suggestions and comments. I have chosen to implement the calls as seperate functions as suggested.Since they do depend on the cmd value, I used that field for dedicated naming of the functions + the appropriate struct. I wrote a small python script to automate the code creation. Again, thank you all for the fast response! Cheers!
74,565,979
74,566,074
Function & array [Getting Max Number]
#include <iostream> using namespace std; int getMax(numbers[], int size){ int max = numbers[0]; for(i=1; i<size; i++){ if(numbers[i] > max) max = numbers[i]; } return max; } int main(){ int numbers[6] = {31,23,45,6,7,-2}; cout << getMax(numbers, 6) << endl; return 0; } I can't seem to get the max number that I wanted from this code. And this is also my first time using stack overflow, so if there isn't enough information. Please spare me :) I am not sure if tried enough soultions to slove this problem. I just wanted to see how stack overflow worked and whether I will get my question answered. :)
The only thing I see wrong with this program are syntax errors. Compiling yields this: error: 'numbers' was not declared in this scope 6 | int getMax(numbers[], int size){ | ^~~~~~~ That's because you forgot to specify the type of the variable numbers. It is an integer array. You can fix this by writing: int getMax(int numbers[], int size) Similarly, you forgot to define i in the loop. Write this: for(int i=1; i<size; i++) Get in the habit of reading the compiler's error messages. They are important, and they are trying to tell you what's wrong. Always read the first error. Subsequent errors may be confusing, due to the flow-on effect of earlier errors.
74,566,265
74,569,293
Defining default constructor results in C2600 {cannot define a compiler-generated special member function (must be declared in the class first)
I'm learning 'modern' C++ and I'm having a really hard time discerning the issue with this code. Ball.h: #ifndef BALL_H #define BALL_H #include <string> #include <string_view> namespace ball { class Ball { std::string _color{}; double _radius{}; public: Ball() = default; Ball(double radius); Ball(std::string_view color = "black", double radius = 10); void print() const; }; } #endif // !BALL_H Ball.cpp: #include "Ball.h" #include <iostream> #include <string_view> namespace ball { Ball::Ball(double radius) { _color = "black"; _radius = radius; } Ball::Ball(std::string_view color, double radius) { _color = color; _radius = radius; } void Ball::print() const { std::cout << "Ball: " << std::endl; std::cout << "\tcolor: " << _color << std::endl; std::cout << "\tradius: " << _radius << std::endl; } } Why does defining Ball() = default; produce a compiler error (complaining about the constructor that takes two arguments, causing further confusion). If I omit the default constructor definition entirely the code compiles and functions perfectly fine. I wish I could be more descriptive, but I'm at a loss here.
The particular error message you are referencing seems to be generated only by older MSVC versions (<= v19.31). It clearly looks like a bug in the compiler to me that has been fixed in later versions. When determining which in-class declaration the out-of-class definition matches, the parameter types should be compared for equivalency irregardless of default arguments. Therefore your definition matches the overload with two parameters, not the defaulted one without any. However, the constructors are not useful with this overload set, as pointed out by the other answer. It will fail as soon as you try to default-construct an object because both overloads would be equally good fits for the initialization in overload resolution, resulting in ambiguity.
74,566,292
74,582,423
Matching multiple objects in a MOCK_METHOD
I am trying to mock a method Handler::Foo to throw an exception that takes in two objects as parameters i.e SomeStruct, SomeClass. The former is created Source::Bar on the fly whereas SomeClass is passed from main. I used MATCHER but it returns a single object which doesn't match with what Foo expects (2 parameters), hence the error. no matching function for call to 'MockHandler::gmock_Foo(MatchMatcherP2<SomeStruct, SomeClass>)' ACTION(MyThrowException) { throw std::invalid_argument("Some exception thrown!"); } TEST(UtClass, TestSourceBar) { auto mockHandler = std::make_shared<MockHandler>(); SomeStruct someStruct = {.a = 10}; SomeClass someClass; EXPECT_CALL(*mockHandler, Foo(Match(someStruct, someClass))) .Times(1) .WillRepeatedly(MyThrowException()); // ERROR } Is there a way to mock Handler::Foo such that it throws an exception? Here's a live sample struct SomeStruct { int a; }; class SomeClass { public: // some methods... }; class Handler { public: virtual void Foo(const SomeStruct&, SomeClass) { // stuff... } }; class Source { std::weak_ptr<Handler> _handler; public: Source(std::weak_ptr<Handler> handler) : _handler(handler) {} void Bar(SomeClass someClass) { SomeStruct s = {.a = 10}; if (auto sp = _handler.lock()) { sp->Foo(s, someClass); // simulate this call } } }; class MockHandler : public Handler { public: MOCK_METHOD(void, Foo, (const SomeStruct&, SomeClass), (override)); }; MATCHER_P2(Match, someStruct, someClass, "") { return arg.a == someStruct.a && arg.someClass == someClass; } ACTION(MyThrowException) { throw std::invalid_argument("Some exception thrown!"); } TEST(UtClass, TestSourceBar) { auto mockHandler = std::make_shared<MockHandler>(); SomeStruct someStruct = {.a = 10}; SomeClass someClass; EXPECT_CALL(*mockHandler, Foo(Match(someStruct, someClass))) .Times(1) .WillRepeatedly(MyThrowException()); // ERROR Source source(mockHandler); source.Bar(someClass); // should throw an exception... }
The matcher is meant to test some conditions for a single argument, so you would need to use a separate matcher for each one. It's not really clear what you want to test here, but one way of doing what your example shows would be: class SomeClass { public: bool operator==(const SomeClass &) const = default; // some methods... }; MATCHER_P(MatchSomeStruct, someStruct, "") { return arg.a == someStruct.a; } MATCHER_P(MatchSomeClass, someClass, "") { return arg == someClass; } TEST(UtClass, TestSourceBar) { auto mockHandler = std::make_shared<MockHandler>(); SomeStruct someStruct = {.a = 10}; SomeClass someClass; EXPECT_CALL(*mockHandler, Foo(MatchSomeStruct(someStruct), MatchSomeClass(someClass))) .Times(1) .WillRepeatedly(MyThrowException()); This will of course check the two parameters separately. If you need to check the two parameters as a whole then you could look into adding a With() clause.
74,566,750
74,566,778
std::equal not working when using vectors returned by a getter
While learning about how std::equal works, I was writing some test code and ran into this problem: #include <iostream> #include <vector> #include <algorithm> class Foo { public: std::vector<int> vec; Foo(std::vector<int> _vec) { vec = _vec; } std::vector<int> get() { return vec; } }; int main() { std::vector<int> x{ 1, 2, 3, 4, 5 }; std::vector<int> y{ 1, 2, 3, 4, 5 }; Foo a = Foo(x); Foo b = Foo(y); std::cout << std::equal(a.vec.begin(), a.vec.end(), b.vec.begin()) << "\n"; // Outputs: 1 std::cout << std::equal(a.get().begin(), a.get().end(), b.get().begin()) << "\n"; // Outputs: 0 <-- why? std::cout << (a.get() == b.get()); // Outputs: 1 } When I compare two vectors that are returned by the getter function, they are not equal. Why is this? I understand that if I return by reference in the method std::vector<int>& get, it'll print that the vectors are equal. However, I might need to use this getter method in a function that takes in a const Foo& argument. However, returning by reference isn't allowed in a const function (std::vector<int>& get() const is not allowed). For my practical purpose, I will need to check that two vectors of doubles are equal by checking if each corresponding element's difference falls within a certain tolerance range. It looks something like this: bool is_equal(double val1, double val2) { return abs(val1 - val2) < 0.0001; } Given 2 Foo objects a and b, I want to check if their vectors are equal (vec is private): std::equal(a.get().begin(), a.get().end(), b.get().begin(), is_equal); // This won't work For this reason I can't really use a.get() == b.get() (I would if I could) because rounding inaccuracies might give unwanted results. Any insight on what's going on and what I can do? Thanks!
First, return by const reference const std::vector<int>& get() const { return vec; } that solves the problem. An alternative would be to have two getters returning the begin and end iterator, instead of returning the vector itself. Second, the reason for the problem is that your version of the getter copies the vector. so in std::equal(a.get().begin(), a.get().end(), b.get().begin()) your iterators a.get().begin() and a.get().end() are pointing at two different vectors (both copies of the vector in the class).
74,567,735
74,567,836
Using set containing strings, How do I pass in each string into function?
I am getting one error in this code where I have commented ERROR LINE. I have a strings containing set called possibleList in the function called wordle and I am trying to pass in each and every string from that set into the wordle function (to recurse) but it gives me an error about rvalue / lvalue and I am not sure how to fix this / make this work. #include <iostream> #include <algorithm> #include <map> #include <set> // #include "wordle.h" // #include "dict-eng.h" using namespace std; // MOST UP TO DATE // Add prototypes of helper functions here // Definition of primary wordle function set<string> wordle(string& in, string& floating, set<string>& dict){ set<string> possibleList; int length = in.length(); // iterate over each letter for(int i = 0; i<length;i++){ cout <<"line 1: "<<char(in[i])<<endl; // only if - if (in[i] == '-'){ for(int j = 97; j<=122; j++){ in[i]=char(j); possibleList.insert(in); } set<string>::iterator itr; for (itr = possibleList.begin(); itr != possibleList.end(); itr++) { wordle(string(*itr), floating, dict); // +++ERROR LINE+++ (LINE 40) } } } // if we reach here, that means that we now have all possibilities in the set return possibleList; } // end of function int main(){ string in = "--pl-"; string floating = "ae"; set<string> dict; // set with 6 strings, should only return 2 of these dict.insert("joshua"); // same dict.insert("phone"); //diff dict.insert("apple"); //same dict.insert("aepll"); //same dict.insert("eapll"); //same dict.insert("ae"); // diff wordle(in, floating, dict); return 0; // how this works: // take all possible strings of the form of size n // then remove all requirements not met } This is the error that I am getting. To repeat from above, I am getting one error in this code where I have commented ERROR LINE. I have a strings containing set called possibleList in the function called wordle and I am trying to pass in each and every string from that set into the wordle function (to recurse) but it gives me an error about rvalue / lvalue and I am not sure how to fix this / make this work. main.cpp: In function ‘std::set<std::__cxx11::basic_string<char> > wordle(std::string&, std::string&, std::set<std::__cxx11::basic_string<char> >&)’: main.cpp:40:24: error: cannot bind non-const lvalue reference of type ‘std::string&’ {aka ‘std::__cxx11::basic_string&’} to an rvalue of type ‘std::string’ {aka ‘std::__cxx11::basic_string’} 40 | wordle(string(*itr), floating, dict); | ^~~~~~~~~~~~
how to fix auto S = *itr; //copy of *iter wordle(S, floating, dict); //use S Because non-const reference can not receive temporary object (as decribed in the error message). For example: //this is error std::string &r = std::string( "xxx" ); //this is ok const std::string &cr = std::string( "xxx" ); //this is ok std::string &&rr = std::string( "xxx" );
74,568,043
74,568,529
I have a question about printf() function
I want to know why the second print function can print a? and the third print function not print a? #include <stdio.h> int main() { int i = 97; // a printf(&i); // a:print content in address &i printf("\n%s\n", &i); // why print a? printf("%c\n", &i); // why not print a? } I want to understand printf function from pointer and memory. Thank you
It depends on what is 'expected'. If it's an address (%s), it will go to and read the contents of that address. If it's a value (%c), it won't go anywhere and take it literally.
74,568,065
74,623,165
how to insert a class instance into RTTR sequential view without getting its wrapped value?
All I am creating a generic binary serializer and got block on how to insert a class instance into a sequential view. Here is the example code: #include <iostream> #include <rttr/type> #include <rttr/registration.h> using namespace rttr; struct Item { int i ; }; struct MyTestClass { std::vector<Item> seq; }; RTTR_REGISTRATION { using namespace rttr; registration::class_<MyTestClass>("TestClass") .constructor<>() .property("seq", &MyTestClass::seq); registration::class_<Item>("Item") .constructor<>() .property("item", &Item::i); } void CreateInst(rttr::instance inst) { auto localobj = inst.get_type().get_raw_type().is_wrapper() ? inst.get_wrapped_instance() : inst; auto p = localobj.get_type().get_property("item"); p.set_value(inst, 100); } int main() { MyTestClass inst; for (auto prop : rttr::type::get_by_name("TestClass").get_properties()) { auto type = prop.get_type(); if (type.is_sequential_container()) { auto val = prop.get_value(inst); auto view =val.create_sequential_view(); view.set_size(1); //just for demo rttr::variant var = view.get_value_type().create(); CreateInst(var); //get its wrapped and insert 'it', it will have the correct result //Item it=var.get_wrapped_value<Item>(); view.set_value(0, var); prop.set_value(inst, val); } } std::cout << inst.seq[0].i << std::endl; } it always output '0' instead of '100' on screen, unless I get its wrapped value and insert. But that is not what I want. Could any expert help me to improve on this ? Thank you. BR Ray
Ok. I finally find the solutions as following: registration::class_<Item>("Item") .constructor<>()(policy::ctor::as_object) .property("item", &Item::i); Remember to add the RTTR_DLL in Project Properties - C/C++-preprocessor -preprocessor definition to avoid the LNK2001 error
74,568,332
74,568,660
print all possible 5 letter words using recursion
I pass in a string, "--pl-" into the function, wordle. I would like the function to return a set of strings with all possible 5 letter words with 'p' as 3rd letter and 'l' as 4th letter. This would mean that the set would return 26^3 different strings. I am trying to use recursion to do this but am not sure how to. #include <iostream> #include <algorithm> #include <map> #include <set> // #include "wordle.h" // #include "dict-eng.h" using namespace std; // MOST UP TO DATE // Add prototypes of helper functions here // Definition of primary wordle function set<string> wordle(string& in, string& floating, set<string>& dict){ set<string> possibleList; int length = in.length(); // iterate over each letter for(int i = 0; i<length;i++){ // only if - if (in[i] == '-'){ for(int j = 97; j<=122; j++){ in[i]=char(j); possibleList.insert(in); } set<string>::iterator itr; for (itr = possibleList.begin(); itr != possibleList.end(); itr++) { auto S = *itr; //copy of *iter wordle(S, floating, dict); //use S } } } // if we reach here, that means that we now have all possibilities in the set return possibleList; } // end of function int main(){ string in = "--pl-"; string floating = "ae"; set<string> dict; // set with 6 strings, should only return 2 of these dict.insert("joshua"); // same dict.insert("phone"); //diff dict.insert("apple"); //same dict.insert("aepll"); //same dict.insert("eapll"); //same dict.insert("ae"); // diff set<string> finalSet = wordle(in, floating, dict); cout << "got here" << endl; set<string>::iterator itr; for (itr = finalSet.begin(); itr != finalSet.end(); itr++) { cout << *itr << endl; } return 0; // how this works: // take all possible strings of the form of size n // then remove all requirements not met } What is happening is that it prints the following: got here a-pl- b-pl- c-pl- d-pl- e-pl- f-pl- g-pl- h-pl- i-pl- j-pl- k-pl- l-pl- m-pl- n-pl- o-pl- p-pl- q-pl- r-pl- s-pl- t-pl- u-pl- v-pl- w-pl- x-pl- y-pl- z-pl- zapl- zbpl- zcpl- zdpl- zepl- zfpl- zgpl- zhpl- zipl- zjpl- zkpl- zlpl- zmpl- znpl- zopl- zppl- zqpl- zrpl- zspl- ztpl- zupl- zvpl- zwpl- zxpl- zypl- zzpl- zzpla zzplb zzplc zzpld zzple zzplf zzplg zzplh zzpli zzplj zzplk zzpll zzplm zzpln zzplo zzplp zzplq zzplr zzpls zzplt zzplu zzplv zzplw zzplx zzply zzplz
The problem in your code is that you do not use the results of the nested recursive call in wordle. In other words, when you fill the possibleList at "level 0", you then have nested calls of wordle, but it is useless currently, cause eveything it does - it does just inside it. That's why you get the result you described. In particular, this happens: At level 0 you fill the list with variations like "a--pl-", "b--pl-", ..., "zzzplz" etc, and collect them in possibleList. And no matter that you have recursive calls, your possibleList is still the same at level 0, and it is returned later - that's what you get as the result. Also, you need to change the way you iterate through different variants. In general words, it could be such (sorry for not giving exact code in C - haven't used if for ages): You first search for the first occurance of _ in your string, remembering it's position. Then you iterate through all possible chars, and substitute this _ with a new char, making a copy of the string. With each new character, you then make a nested call with that new string. You could also pass the current position, so it will know where to start exactly, but that's more an optimisation. The nested call will return you a set of combinations. Which you need to merge with a set at your current level. You then return your accumulated set. Note that you don't need to iterate through all _ in a string explicitly in your method, because it will be done recursively: each new level finds it's own first _ in the string. UPD: Pseudo-code FUNCTION wordleRecursive(str, start=0): possibleList = [] foundPlaceHolder = False FOR (i=start; i<str.length; i++): IF str[i] == '_': foundPlaceHolder = True FOR (j=97; j<122; j++): newStr = copy(str) newStr[i] = char(j) nestedList = wordleRecursive(newStr, i + 1) possibleList = merge(possibleList, nestedList) // We need to find only first occurance BREAK // This is needed if the substring does not contain "_" anymore // in this case we need to return the list with a single item, // Containing the str itself. IF NOT foundPlaceHolder: possibleList = [str] RETURN possibleList
74,568,366
74,574,192
How to get serial number in digital persona finger print sdk in c++
I downloaded and run a C++ project for Digital-persona-sdk https://github.com/iamonuwa/Digital-Persona-SDK/ finger print project.That have two projects in after install the sdk. That project only Capture and Verification function only written.Not written for get serial number. Does anyone have an sample program for solving this problem?
Two minutes of reading the provided documentation tells you everything you need to know: Use DFPEnumerateDevices to get all device GUIDs Call DPFPGetDeviceInfo to get device info for each device in turn. Serial number is embedded in the device info as devInfo->HwInfo.szSerialNb.
74,569,082
74,569,166
How to know which header file to include for a documented function while developing for MacOS?
I'm new to macOS development, so pardon my simplistic question. Say, if I have a function. Let's take SCError for example. From the documentation I can see that I need to add: System Configuration framework But how do I know which header file to add, so that I don't get Use of undeclared identifier 'SCError'? PS. I'll give an example of a documentation that doesn't make me ask these questions. Say, GetLastError. It states at the bottom of the page: Header: errhandlingapi.h (include Windows.h) So it's clear for me what to do: #include Windows.h So what am I missing with the Apple documentation?
Let Xcode help. You know the framework is "System Configuration" by looking at the documentation. So in your source file start typing: #import <Sy and Xcode will start offering suggestions. And the first one you see after entering the above just happens to be for what you need: #import <SystemConfiguration/SystemConfiguration.h> The basic pattern will work for most frameworks. #import <FrameworkName/FrameworkName.h> Again, let Xcode show you likely candidates as you start typing the first few letters. Then it's easy to select the match so the rest is entered for you.
74,569,775
74,577,159
Handling curly braces in curl/libcurl
From the command line, I have a curl request with two query parameters that use curly braces. However, one only works when URL-encoded and the other only works when it is not URL-encoded. Here's an example of a request that (weirdly) works from the command line and returns data for 3 IDs. I wouldn't expect it to work because TIME is URL-encoded with curly braces (%7B and %7D) but P_ID is not: curl -X GET "https://example.com/search?TIME=%7B%22TIME_TYPE%22%3A%22MESSAGE%22%2C%22MESSAGENUMBER%22%3A5%7D&P_ID={1,2,3}" Even weirder, the following calls don't work and seem to ignore the P_ID field and give me data for every person: curl -X GET "https://example.com/search?TIME=%7B%22TIME_TYPE%22%3A%22MESSAGE%22%2C%22MESSAGENUMBER%22%3A5%7D&P_ID=%7B1,2,3%7D" curl -X GET "https://example.com/search?TIME=%7B%22TIME_TYPE%22%3A%22MESSAGE%22%2C%22MESSAGENUMBER%22%3A5%7D&P_ID=1&P_ID=2&P_ID=3" curl -X GET "https://example.com/search?TIME={%22TIME_TYPE%22%3A%22MESSAGE%22%2C%22MESSAGENUMBER%22%3A5}&P_ID=1&P_ID=2&P_ID=3" Given these constraints, where the first call works as I want it to, but the second and third do not, then how do I use libcurl in C++ such that the first call is replicated? I know CURLOPT_URL encodes everything, so it would encode both the braces in TIME and P_ID. I've tried using CURLUPART like below, but to no avail. void *curlHandle; curl_easy_reset(curlHandle); CURLU *url = curl_url(); curl_url_set(url, CURLUPART_URL, "example.com", 0); curl_url_set(url, CURLUPART_QUERY, "P_ID={1,2,3}", CURLU_APPENDQUERY); curl_url_set(url, CURLUPART_QUERY, "TIME=%7B%22TIME_TYPE%22%3A%22MESSAGE%22%2C%22MESSAGENUMBER%22%3A5%7D", CURLU_APPENDQUERY); curl_url_set(url, CURLUPART_SCHEME, "https", 0); curl_url_set(url, CURLUPART_PATH, "/search/", 0); curl_easy_setopt(curlHandle, CURLOPT_CURLU, url); curl_easy_perform(curlHandle); I'm getting this response: * No URL set Curl failed with error 3: URL using bad/illegal format or missing URL. 0 retries remaining In summary: how do I get libcurl to make a bizarre curl request like the first one up top? Because that is the only way I can execute from the command line with the expected result of only getting the 3 people's data. Alternatively, is there perhaps another way to try this curl request other than the 4 attempts above? Should I just reach out to the API owner and ask why it likes { encoded in some places and not others?
These are your 4 query strings after being url decoded. TIME={"TIME_TYPE":"MESSAGE","MESSAGENUMBER":5}&P_ID={1,2,3} TIME={"TIME_TYPE":"MESSAGE","MESSAGENUMBER":5}&P_ID={1,2,3} TIME={"TIME_TYPE":"MESSAGE","MESSAGENUMBER":5}&P_ID=1&P_ID=2&P_ID=3 TIME={"TIME_TYPE":"MESSAGE","MESSAGENUMBER":5}&P_ID=1&P_ID=2&P_ID=3 None of the characters in your query strings need to be urlencoded. Given you basically have two urls. These are both urls, and the query strings url decoded on the server: https://example.com?TIME={"TIME_TYPE":"MESSAGE","MESSAGENUMBER":5}&P_ID=1&P_ID=2&P_ID=3 TIME={"TIME_TYPE":"MESSAGE","MESSAGENUMBER":5}&P_ID=1&P_ID=2&P_ID=3 https://example.com?TIME={"TIME_TYPE":"MESSAGE","MESSAGENUMBER":5}&P_ID={1,2,3} TIME={"TIME_TYPE":"MESSAGE","MESSAGENUMBER":5}&P_ID={1,2,3} I do not think your query string is causing the error. It appears you got this wrong: CURLU *url = curl_url(); Maybe it should be: CURLU *url= curl_url(); curl_url_set(url, CURLUPART_URL, R"(https://example.com?TIME={"TIME_TYPE":"MESSAGE","MESSAGENUMBER":5}&P_ID={1,2,3})", 0); Or just pass the URL directly to the easy handle: curl_easy_setopt(curlHandle, CURLOPT_URL, R"(https://example.com?TIME={"TIME_TYPE":"MESSAGE","MESSAGENUMBER":5}&P_ID={1,2,3})");
74,570,656
74,570,867
A question about c++ threads exception handling
Demo code: #include <exception> #include <future> #include <iostream> #include <stdexcept> #include <thread> void func1() { std::cout << "Hello func1\n"; throw std::runtime_error("func1 error"); } int main() { try { std::future<void> result1 = std::async(func1); result1.get(); } catch (const std::exception &e) { std::cerr << "Error caught: " <<e.what() << std::endl; } } Output: Hello func1 Error caught: func1 error It seems that the main function can catch exception from thread. But based on this question & answer , the main function should not be able to catch thread exception. It confused me. Maybe I mis-understand some information. Could anyone give some tips? Thanks in advance.
First things first, std::async and std::thread are not the same thing at all. Moreover, std::async is not required to execute the callable into another thread, it depends on the launch policy you used. I would suggest you to read the documentation about std::async. But either way, any thrown exception are already handled by std::async and are stored in the shared state accessible through the returned std::future, which means the exceptions, if any, are rethrowned when you call std::future<T>::get() (which happens in the main thread in your case).
74,570,683
74,574,688
Use pthread_cancel in QNX system has a memory leak, but it does not exist on the Linux system
I have a code, main thread create 2 thread(thread_1 and thread_2), I use pthread_cancel to cancel thread_1 in thread_2, but the data that I create in thread_1 will not be destructored when I run it in QNX system, but there is no problem in Linux system. It my test code, when I run it in QNX system,MyClass and MyClass2 object destructor not be called, so the 100M memory will leak; but run it in Linux system,it will call MyClass and MyClass2 object destructor. why is there such a difference??? #include <iostream> #include <pthread.h> #include <thread> using namespace std; pthread_t thread_id_1; pthread_t thread_id_2; class MyClass2 { public: MyClass2() { cout << "Build MyClass2" << endl; } ~MyClass2() { cout << "Destory MyClass2" << endl; } }; class MyClass { public: MyClass() { cout << "Build MyClass" << endl; p = (char *)malloc(1024 * 1024 *100); } ~MyClass() { cout << "Destory MyClass" << endl; free(p); } char *p; }; void func(int i) { MyClass2 c2; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); cout << "thread 1 func:" << i << endl; } static void *thread_1(void *arg) { MyClass my_class; int type_value = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); cout << "thread_1 set cancle type+++++:" << type_value << endl; for (int i = 0; i < 10; i++) { func(i); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } return nullptr; } static void *thread_2(void *arg) { for (int i = 0; i < 10; i++) { cout << "thread_2:" << i << endl; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } int ret = pthread_cancel(thread_id_1); cout << "otx_thread_2 cancel thread 1 ret:" << ret << endl; return nullptr; } int main(int argc, char *argv[]) { cout << "Main start" << endl; pthread_attr_t attr; pthread_attr_init( &attr ); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); cout << "Main set detch" << endl; if (pthread_create(&thread_id_1, &attr, thread_1, nullptr) != 0) { cout << "pthread_create() 1 error" << endl; return -1; } if (pthread_create(&thread_id_2, nullptr, thread_2, nullptr) != 0) { cout << "pthread_create() 2 error" << endl; return -1; } if (pthread_join(thread_id_2, NULL) != 0) { cout << "pthread_join() 1 error"; return -1; } while (1) { cout << "Main Loop" << endl; std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } return 0; } enter image description here enter image description here I try it again and again, so I confirm that there is no problem with the code, But I don't understand why there is such a difference
pthread_cancel is outside the scope of the C++ specification. C++ does not specify its behavior, nor inherit it from C or POSIX. The difference is simply because QNX and Linux have implemented pthread_cancel differently in a C++ environment. There is literally nothing more to it than that. I imagine that the QNX implementation stops the thread in its tracks, whereas the Linux implementation probably induces an exception which unwinds the canceled thread's stack.
74,570,742
74,570,837
Access element from nlohmann::json?
I want to access element from a json which is the response from one query. The json structure is : json = { "result": { "12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq": [ 20964, 347474, 347475 ], "12ashmTiFStQ8RGUpi1BTCinJakVyDKWjRL6SWhnbxbT": [ 1992, 1993, 109096 ], }} I want to get the 1st element(result[0]) key from result object ie 12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq in some variable a and the corresponding array ie [20964, 347474,347475 ] in some varible b. The problem I am having is that 1st element key value in this case "12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq" always changes for every query! Can someone show me the way how can I access it correctly?
json.begin() will give you an iterator pointing to the first element. Then you can access its' key and value using: auto key = json.begin().key(); auto value = json.begin().value();
74,570,952
74,571,195
Initialize a character array from a constexpr string
I had code similar to this: #define STR "ABC" // ... char s[] = STR; puts(s); s[2] = '!'; puts(s); And I tried to modernize it with constexpr: constexpr char STR[] = "ABC" // ... char s[] = STR; puts(s); s[2] = '!'; puts(s); But it no longer compiles. How can I initialize a string on the stack from a constexpr constant without runtime penalty?
C-style arrays can only be initialized by literals, not by another array or const char*. You can switch to std::array constexpr std::array<char,4> STR{"ABC"}; int main() { std::array s{STR}; // OR: auto s{STR}; } Unfortunately, it requires specifying the length of the string literal in STR, if you have C++20, you can use std::to_array: constexpr std::array STR{std::to_array("ABC")}; optionally replacing std::array with auto. If you do not have C++20, you can still use the implementation from the link above to write your own to_array. There is also std::string_view and std::span but both are non-owning pointers.
74,571,491
74,571,838
Importing text from a .txt file into a 2D array of strings
I've been trying to import text from a .txt file into a 2D array of string, but it doesn't seem to be working. Each row in the .txt file has three values/elements separated that I need to copy. This is the code: // i am only allowed to use these libraries. #include <iostream> #include <fstream> #include <string> #include <stdlib.h> using namespace std; int main() { const int rows = 38; const int columns = 3; string companies[rows][columns]; // Inputting file contents ifstream file; file.open("companies.txt"); while(!file.eof()) { for(int i = 0; i < 38; i++) { for(int j = 0; j < 3; j++) { getline(file, companies[i][j], ','); } } } file.close(); cout << endl << endl; // displaying file contents using for loop for(int i = 0; i < 38; i++) { for(int j = 0; j < 3; j++) { cout << companies[i][j] << endl << endl; } } cout << endl << endl; return 0; } This is the data that I want to import : Symbol,Company Name,Stock Price ATRL,Attock Refinery Ltd.,171.54 AVN,Avanceon Ltd. Consolidated,78.1 BAHL,Bank AL-Habib Ltd.,54.97 CHCC,Cherat Cement Company Ltd.,126.26
One of the problems with your code is that you are only looking for , as a delimiter and not handling line breaks between the rows at all. Normally, I would suggest reading each row into a std::istringstream and then use std::getline(',') to parse each stream, but you say that you are not allowed to use <sstream>, so you will just have to parse each row manually using std::string::find() and std::string::substr() instead. Also, using while(!file.eof()) is just plain wrong. Not just because it is the wrong way to use eof(), but also because your for loops are handling all of the data, so there is really nothing for the while loop to do. Try something more like this instead: #include <iostream> #include <fstream> #include <string> using namespace std; int main() { const int max_rows = 38; const int max_columns = 3; string companies[max_rows][max_columns]; string line; string::size_type start, end; // Inputting file contents ifstream file("companies.txt"); int rows = 0; while (rows < max_rows && getline(file, line)) { start = 0; for(int j = 0; j < max_columns; ++j) { end = line.find(',', start); companies[rows][j] = line.substr(start, end-start); start = end + 1; } ++rows; } file.close(); cout << endl << endl; // displaying file contents using for loop for(int i = 0; i < rows; ++i) { for(int j = 0; j < max_columns; ++j) { cout << companies[i][j] << endl << endl; } } cout << endl << endl; return 0; } Online Demo
74,571,883
74,574,807
For loop and Arrays [C++ Simple ATM system]
So I am trying to create a ATM system that lets user to input value such as Account number, account name and amount. But I can't figure out what exactly I have to do int AccNum[2]; string AccName[2]; float AccBal[2]; cout << "********** ENTER ACCOUNT **********"<<endl; for(int num = 0; num < 2; num++){ cout << "Enter Account number: "; cin >> AccNum[num]; for(int name = num; name < 2; name++){ cout << "Enter Account Name: "; getline(cin, AccName[name]); for(int bal = name; bal < 2; bal++){ cout << "Enter Amount: "; cin >> AccBal[bal]; } } } I have tried something like this but it does not give the result that I want. The ideal result would be ********** ENTER ACCOUNT ********** Enter Account number: 1231232 Enter Account name: James white Enter amount: 1000 it will run 2 times so there would be 2 accounts after this loop that will have a result like this ********** THE ACCOUNT IS ********** Account number: 1231232 Account name: James white Balance: 1000
So the code you wrote is nearly good. Too many loops in my opinion int AccNum[2]; string AccName[2]; float AccBal[2]; cout << "********** ENTER ACCOUNT **********"<<endl; for(int num = 0; num < 2; num++){ // lets call this loop a. happens 2 times cout << "Enter Account number: "; cin >> AccNum[num]; for(int name = num; name < 2; name++){ // loop b happens 2 times * loop a times cout << "Enter Account Name: "; getline(cin, AccName[name]); for(int bal = name; bal < 2; bal++){ loop c = 2 * a * b = 8 cout << "Enter Amount: "; cin >> AccBal[bal]; } } } Direct fix: int main() { int AccNum[2]; string AccName[2]; float AccBal[2]; cout << "********** ENTER ACCOUNT **********" << endl; for(int num = 0; num < 2; num++){ cout << "Enter Account number: "; cin >> AccNum[num]; cout << "Enter Account Name: "; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); getline(cin, AccName[num]); cout << "Enter Amount: "; cin >> AccBal[num]; } for(int i = 0; i < 2; i++) cout << "********** ENTER ACCOUNT **********" << endl << "Account number: " << AccNum[i] << endl << "Account name: " << AccName[i] << endl << "Balance: " << AccBal[i] << endl << endl; } But if you want to expand it a little bit: #include <iostream> #include <vector> using namespace std; struct Account { int Number; string Name; float Balance; Account(int num, string nam, float bal) : Number(num), Name(nam), Balance(bal) {} Account() {} void getData() { cout << "Enter Account number: "; cin >> Number; cout << "Enter Account Name: "; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); getline(cin, Name); cout << "Enter Amount: "; cin >> Balance; } void printAccount() { cout << "********** ENTER ACCOUNT **********" << endl << "Account number: " << Number << endl << "Account name: " << Name << endl << "Balance: " << Balance << endl << endl; } }; int main() { vector<Account> accounts; for(int i = 0; i < 2; i++) { Account person; person.getData(); accounts.emplace_back(person); } for(int i = 0; i < 2; i++) accounts[i].printAccount(); } Both codes give the exact same output:
74,572,355
74,640,847
What happened with TensorFlow Lite documentation for the Interpreter class
I started working on a project using TensorFlow Lite in C++. I have often looked up information about the API in the official reference. Almost all of the methods are used were listed in the Interpreter class. However, a few days ago I noticed, that the Interpreter class has been completely removed from the documentation. Other classes are still listed there. When searching for methods only present in the C++ API like typed_input_tensor, search results show class reference for `tflite::Interpreter``, but only return 404 when followed. Does anyone have any idea is the class reference moved to a different place, or removed alltogether?
I turns out it was just a temporary bug, everything works now, thanks Karim for pointing it out.
74,572,508
74,572,632
How can I change an object's attributes with function?
Forgive me if the title isn't specific enough. Let's say I want to make an RPG. I make a class for the characters. I then make an array that function as a party of characters. Then I have a function that reduced the HP of the first member of a party. ` #include <iostream> #include <string> class Chara { public: int HP; Chara(int health) { HP = health; } }; int Battle(Chara Party[2]) { Party[0].HP -= 2; } int main() { Chara Final(0); Chara Fantasy(7); Chara Player[2] = {Final, Fantasy}; Battle(Player); std::cout << Final.HP; } ` However, the HP of the character doesn't change. Is there something that I can do to make it so that the character's HP actually changes?
You have two separate problems caused by C++ passing structs by copy. First, the line Chara Player[2] = {Final, Fantasy}; creates an array of Chara and initializes the members with copies of the mentioned variables. That means that the final line will not see any modifications made to elements of Player. Instead, you should do: Chara Player[2] = { Chara{0}, Chara{7} }; // and optionally, if you still want to access individual members: Chara& Final = Player[0]; Chara& Fantasy = Player[1]; Secondly, you pass Player to the Battle function by copy. Thus, any changes made to Party inside the function are not reflected in the outer Player variable. The quick fix is to take Party by pointer instead: void Battle(Chara* Party) { ... } This works because arrays can decay to pointers to their first element when passed. As best practice, you should probably use a std::vector instead, which allows you to dynamically add and remove party members and has all kinds of helpful methods.
74,573,540
74,573,619
Why can this C++ child class be constructed by objects of parent class type
class AAA { int m_Int; public: AAA() : m_Int{12} {} }; class BBB { int m_Int1; public: BBB() : m_Int1{12} {} }; class CCC : public AAA, public BBB {}; AAA a; BBB b; CCC c{ a, b }; Why can object c be constructed by parent class object? I tried to find out which standard support this syntax. I wrote the code with Visual Studio, and I found C++ 14 does not support this, but C++17 does. I also found that the construct process of c call AAA and BBB's copy constructor. I want to know what the syntax is and where to find the item.
This is aggregate initialization. Since C++17, CCC is an aggregate, where one of the requirements was relaxed from "no base classes" to "no virtual, private, or protected base classes".
74,573,922
74,573,997
What does the expression std::string {} = "..." mean?
In this code: #include <iostream> int main(void) { std::string {} = "hi"; return 0; } This type of declaration is valid in C++. See in Godbolt. What does it mean? How is it valid? For information, I tested this program from c++11 to c++20 flags as extended initializers are available from c++11 onwards.
std::string::operator=(const char*) is not &-qualified, meaning it allows assignment to lvalues as well as rvalues. Some argue(1) that assignment operators should be &-qualified to ban assignment to rvalues: (1) E.g. the High Integrity C++ standard intended for safety-critical C++ development, particularly rule 12.5.7 Declare assignment operators with the ref-qualifier &. struct S { S& operator=(const S&) & { return *this; } }; int main() { S {} = {}; // error: no viable overloaded '=' } Or, more explicitly: struct S { S& operator=(const S&) & { return *this; } S& operator=(const S&) && = delete; }; int main() { S {} = {}; // error: overload resolution selected deleted operator '=' }
74,574,238
74,574,293
Is it possible to do a two-step initialization of a non-movable object in the member initializer list?
Is it possible to do a two-step initialization of a non-movable object in the member initializer list using C++17? Here is the legacy API I’m working with (and yes I know it’s bad but I can’t change it) class A { public: A(int some_param); // no default, move or copy constructor nor assignment A() = delete A(const& A) = delete; A(const&&) = delete; // it shouldn’t be deleted, but I’m not able to modify that class A& operator= (const& A) = delete; A& operator= (const&&) = delete; // and it uses two phase construction void init(int some_other_argument); // more stuff }; class B { public: // no default constructor, and must be created with a fully-initialized A B() = delete; B(const& A); // more stuff }; And here is what I am trying to write: class C { public: C(); private: A m_a; B m_b; }; C::C() : m_a{ /* two step initialization of A*/} , m_b(m_a) {} The usual trick of using a immediately initialize lambda doesn’t work: C::C() : m_a{[] { auto a = A(0xdead_beef); a.init(42); return a; // doesn’t compile because A isn’t movable }()} , m_b(m_a) {} Nor does using the body of the constructor: C::C() // m_a and m_b will be default-initialized here, but their default initializer are deleted { m_a = A(0xdead_beef); m_a.init(); m_b = B(m_a); } And nor doing the second step of the two step initialization in the body of the constructor: C::C() : m_a(0xdead_beef) , m_b(m_a) // m_a isn’t fully initialized here { m_a.init(); } Currently I’m using a unique_ptr for m_b, but I was asking myself if there was a better solution. class C { public: C(); private: std::unique_ptr<A> m_a; // guaranted to be initialized in the constructor, no need to check before dereferencing B m_b; }; C::C() : m_a{[] { auto a = new A(0xdead_beef); a->init(42); return a; }()} , m_b(*m_a) {} I think the rules of guaranteed move elision were improved in C++20, but I’m still using C++17.
You might still abuse of comma operator: C::C() : m_a{ 0xdeadbeef }, m_b((m_a.init(42), m_a)) {}
74,574,468
74,574,631
How is that possible that these two pieces of code have the same memory usage?
First case: #include <vector> int main() { const int iterations = 1'000'000; std::vector<const char *> c; for (int i = 0; i < iterations; i++) { c.push_back("qwertyuiopqwertyuiopqwertyuiopqwertyuiopqwertyuiop"); } } Second case: #include <vector> int main() { const int iterations = 1'000'000; std::vector<const char *> c; for (int i = 0; i < iterations; i++) { c.push_back("qwerty"); } } In both cases the shown memory usage of the active process is about 11 MB. The first thought was that the memory usage refers only to the pointers size, but then how should i know from outside how much memory does a certain software uses? ( Without expliciting calculating the size from inside the code) Edit: I thought that with c.push_back("qwerty") i was creating a new string every time. That was my objective. I managed to do it now by modifing the code in this way: #include <vector> int main() { const int iterations = 1'000'000; std::vector<const char *> c; for (int i = 0; i < iterations; i++) { std::string* s = new std::string("sadadasd"); c.push_back((*s).c_str()); } } It looks awful but at least now the memory usage makes sense. Is there a more elegant way to achieve this?( I mean without introducing std::string and using only const char*)
A pointer takes up (usually) 8 bytes. In both cases you create a vector with a million identical pointers. So that's 8 million bytes for the vector data. Total memory usage depends on more things, like how much empty space is in the vector, and how much memory is used by the rest of the process. Both programs only include one copy of the string. The extra 44 bytes are a drop in the bucket. The second program might not even use an extra 44 bytes, if they were unused padding bytes anyway - which is likely, since the OS can only allocate memory in 4096-byte chunks called pages.
74,575,199
74,576,151
Data races resolution C++
I wanted to ask for some help in solving the data races in my program. I started with a simulation of how things should work if I were using multithreading and then modified the code so that I can check if I really obtain those results but I don't know how to resolve the data races in the code. Can someone help me please? My code is the following: void pi(size_t& id, size_t nThread, size_t N, double& pigreco) { size_t begin = id* N / nThread; size_t end = (id+ 1) * N / nThread; random_device rd; // Object to create random seed mt19937 generator(rd()); // Mersenne Twister seeded with rd() uniform_real_distribution<double> distribution(-1.0, 1.0); for (size_t i = begin; i < end; i++) { double x = distribution(generator); double y = distribution(generator); if (sqrt(x*x + y*y) < 1.0) pigreco += 4.0 / double(N); } } int main(int argc, char* argv[]) { if (argc != 2) { cerr << "Usage: ./pi <number of threads>" << endl; exit(EXIT_FAILURE); } size_t nThread = (size_t)atoi(argv[1]); size_t N = 100000000; cout << "Generating " << N << " random values using " << nThread << " thread(s)." << endl; atomic<double> pigreco = 0.0; // create threads vector<thread> threads(nThread); for (size_t i = 0; i < nThread; i++) threads[i] = thread(pi, ref(i), nThread, N, ref(pigreco)); for_each(threads.begin(), threads.end(), mem_fn(&thread::join)); cout << "Estimated value for pi: " << pigreco << endl; exit(EXIT_SUCCESS); } I tried using valgrind in order to find the possible data races and I found out that there is one at the first for loop of the main, I think probably because I use 'i' as argument of my function but that I don't know how to resolve it.
I don't know how to resolve the data races in the code. Then stop using std::thread, and especially stop passing references to functions on those threads. Here is one way you could avoid passing any references between threads: #include <cstdlib> #include <iostream> #include <random> #include <future> #include <algorithm> int pimontecarlo(size_t iterations) { int count = 0; std::random_device rd; std::mt19937 generator(rd()); std::uniform_real_distribution<double> distribution(-1.0, 1.0); for (size_t i = 0; i < iterations; i++) { double x = distribution(generator); double y = distribution(generator); if (sqrt(x*x + y*y) < 1.0) ++count; } return count; } int main(int argc, char* argv[]) { if (argc != 2) { std::cerr << "Usage: ./pimontecarlo <number of threads>" << std::endl; exit(EXIT_FAILURE); } size_t numThreads { atoi(argv[1]) }; size_t N = 100000000; std::cout << "Generating " << N << " random values using " << numThreads << " thread(s)." << std::endl; // create futures std::vector<std::future<int>> results(numThreads); for (auto & result : results) result = std::async(pimontecarlo, N / numThreads); int count = 0; for (auto & result : results) count += result.get(); double pi = (4.0 * count) / N; std::cout.precision(12); std::cout << "Estimated value for pi: " << pi << std::endl; exit(EXIT_SUCCESS); } See it on coliru
74,575,308
74,575,409
waiting threads status while mutex gets released at the end of a loop in wait_for function in C++
Suppose we have four threads in this order (D, C, B, A) waiting in a queue, and 'r.cv.notify_all()' just gets invoked, and suppose thread A (first thread in the queue) locks the mutex and the lambda returns true, after thread A reaches the end of the while loop, the lock is going to be released as it follows the RAII rule so my question is if the lock gets released at the end of the loop, is thread B going to acquire it, or still the lock belongs to thread A (as its job hasn't finished yet) void operator() (SharedData& r, std::chrono::system_clock::time_point tToc) { unsigned short tempValue = r.value; Debug::out("Befooooooooooooooooooreee \n"); while (std::chrono::system_clock::now() < tToc) { std::unique_lock<std::mutex> lock(r.mtx); // ---> "A B C D" four threads if (r.cv.wait_until(lock, tToc, [&] { Debug::out("TEstttttttt -> temp %x \n", tempValue); Debug::out("TEstttttttt -> value %x \n", r.value); return (r.value != 0 && r.value != tempValue); } )) { r.complement = ~(r.value); Debug::out("AAAAAAAfterrrrrrrrrrfrrrr \n"); tempValue = r.value; } } }
after thread A reaches the end of the while loop, the lock is going to be released ... ... and, that's it. That's the end of the story. The lock is released. We're outta here. ... or still the lock belongs to thread A No, it does not belong to any thread. We've just determined that the lock is released. A released lock, by definition, is no longer locked. It is no longer owned by any execution thread. Once the lock is released it's up for grabs to be locked by any other thread, either an execution thread that decided to lock it, for some reason, or an execution thread that was patiently waiting to acquire the lock, but could not (because some other execution thread was hoarding it). So, presuming that the locking semantics are internally implemented in the manner you described: the next thread will acquire the lock. ... (as its job hasn't finished yet) Whatever the thread's high level "job" is, and whether that high level job is finished, or not, is immaterial. The only thing that matters, when it comes to locking semantics, is: is the mutex locked or not. That's it. Mutexes are just small, low-level peons. They have no clue whatsoever, what might be some high level "job" that they're task to accomplish. They are just a cog in a wheel. All they know is whether they are locked, or not. That's it.
74,575,620
74,584,466
How to make an overloaded function a dependent name, so two-phase lookup finds it?
Look at this example: template <typename TYPE> struct Foo { static constexpr auto a = bar(TYPE()); static constexpr auto b = static_cast<int (*)(TYPE)>(bar); }; struct Bar {}; constexpr int bar(Bar) { return 42; } int main() { auto a = Foo<Bar>::a; auto b = Foo<Bar>::b; } At the definition of Foo, bar is unknown to the compiler. But it's a not a problem at the initialization of Foo::a, because bar(TYPE()) is a dependent expression, so ADL lookup will find bar later at the second phase of lookup. But it's a problem at the initialization of Foo::b, because bar is not a dependent expression, so the compiler complains that bar is undeclared (godbolt). So I can call bar (Foo::a), but I cannot take its address (Foo::b). Is there any trick so can I get the address of bar (besides the obvious solution that I move Foo after bar)? For example, somehow make an expression which is dependent on TYPE and returns bar's address?
You can’t, unfortunately: even if bar were somehow dependent, ADL would never be performed for it since it isn’t a function being called. (Put differently, unqualified names that aren’t the function name in a dependent call are always looked up in the template definition.) The closest you can do is to use (and specialize!) a trait and write bar_trait<TYPE>::bar or make your own wrapper function for bar and take the address of that (which might or might not be good enough).
74,576,092
74,576,300
How to get my pi generating code to cut off at 300?
I am trying to write a program that allows for pi to be gernated to the 300th digit, but I cannot seem to figure out how to cut it off at the 300th digit. As of right now the code was ran forever and any other method I have tried has not worked like cutting off at a specfiec time, however this is not what I need to happen. #include <iostream> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; class Gospers { cpp_int q, r, t, i, n; public: // use Gibbons spigot algorith based on the Gospers series Gospers() : q{1}, r{0}, t{1}, i{1} { ++*this; // move to the first digit } // the ++ prefix operator will move to the next digit Gospers& operator++() { n = (q*(27*i-12)+5*r) / (5*t); while(n != (q*(675*i-216)+125*r)/(125*t)) { r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r); q = i*(2*i-1)*q; t = 3*(3*i+1)*(3*i+2)*t; i++; n = (q*(27*i-12)+5*r) / (5*t); } q = 10*q; r = 10*r-10*n*t; return *this; } // the dereference operator will give the current digit int operator*() { return (int)n; } }; int main() { Gospers g; std::cout << *g << "."; // print the first digit and the decimal point for(300;) // run forever { std::cout << *++g; // increment to the next digit and print } }
You are stating that you generating 300 digits, however this for-loop is broken: for(300;) It is not valid C++ code, as a for-loop is structured like this: for ( declaration ; expression ; increment) While all 3 segments are optional, you do need at least two semicolons (;) for a valid syntax. To achieve a for loop that repeats a sequence 300 times you would need a for loop-like this: for (int i = 0; i < 300; ++i)
74,576,426
74,576,635
Iterate using iterators on nlohmann::json? Error: invalid_iterator
Continuing my previous question here, Now I want to insert the keys and values present in the below json into a std::vector<std::pair<std::string, std::vector<uint64_t>>> vec; Keys here are this strings: 12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq , 12ashmTiFStQ8RGUpi1BTCinJakVyDKWjRL6SWhnbxbT values corresponding them are list:[20964,347474, 34747],[1992,1993,109096] This is the json which is response from query. j = { "12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq": [ 20964, 347474, 347475 ], "12ashmTiFStQ8RGUpi1BTCinJakVyDKWjRL6SWhnbxbT": [ 1992, 1993, 109096 ] } To try first I have tried to insert only first element's key and value. It is working correctly. std::vector<std::pair<std::string, std::vector<uint64_t>>> vec; auto key = j.begin().key(); auto value = j.begin().value(); vec.push_back(std::make_pair(key, value)); Now I am trying this way to insert all the key values in vector std::vector<std::pair<std::string, std::vector<uint64_t>>> vec; int i = 0; while ((j.begin() + i) != j.end()) { auto key = (j.begin() + i).key(); auto value = (j.begin() + i).value(); vec.push_back(std::make_pair(key, value)); i++; } I am getting the error: [json.exception.invalid_iterator.209] cannot use offsets with object iterators Can someone please what is the correct way of doing this ?
I think you're over complicating this. You can iterate over a json object the same way you would any other container using a for loop: #include "nlohmann/json.hpp" #include <iostream> int main() { nlohmann::json j = nlohmann::json::parse(R"({ "12CUDzb3oe8RBQ4tYGqsuPsCbsVE4KWfktXRihXf8Ggq": [ 20964, 347474, 347475 ], "12ashmTiFStQ8RGUpi1BTCinJakVyDKWjRL6SWhnbxbT": [ 1992, 1993, 109096 ] })"); std::vector<std::pair<std::string, std::vector<uint64_t>>> vec; for (auto it = j.begin(); it != j.end(); ++it) { vec.emplace_back(it.key(), it.value()); } for (auto& it : vec) { std::cout << it.first << ": "; for (auto& value : it.second) { std::cout << value << ", "; } std::cout << "\n"; } } If you don't care about the order of items (JSON keys are unordered anyway and nlohmann doesn't preserve the order by default) then you can do this in a one liner: std::map<std::string, std::vector<uint64_t>> vec = j;
74,576,589
74,576,943
Force decay of string literals (const char array) to ptr
In the following example I try to emplace_back() a string literal and a string_view into an std::pair of string_views. However, my problem is that emplace_back() takes up the string literal as a const char array and doesn't decay it to a pointer. The consequence is that emplace_back() can't find std::string_view's const char* constructor. How can I decay string literals manually as parts of function arguments (that are aggressively gobbled up by universal references)? Demo #include <utility> #include <vector> #include <string> #include <string_view> #include <cstdio> struct A { std::string_view vsn_ = "0.0.1"; std::string_view key_; }; auto get_url(A params = {}) { std::vector<std::pair<const char*, std::string_view>> queries; if (!params.key_.empty()) { queries.emplace_back(std::piecewise_construct, ("key="), params.key_); } if (!params.key_.empty()) { queries.emplace_back(std::piecewise_construct, ("VSN="), params.vsn_); } std::string url; for (auto q : queries) { url += q.first; url += q.second.data(); } return url; } int main() { printf("%s", get_url().data()); } (As you can see I already tried to put parantheses around the string literals to no avail)
A std::piecewise_construct constructor (as you are trying to use here for the std::pair construction) expects the rest of the arguments to be std::tuples with each tuple holding the arguments to construct one of the pieces (e.g. pair elements). You are not passing tuples as second and third parameter, so it can't work. It should be queries.emplace_back(std::piecewise_construct, std::forward_as_tuple("key="), std::forward_as_tuple(params.key_)); However, if you want construction of each pair element from just one argument, you don't need the piecewise constructor. std::pair has a constructor specifically for that: queries.emplace_back("key=", params.key_); None of this has anything to do with whether or not the array is decayed to a pointer. (It will be decayed where that is required, no manual intervention required.)
74,577,005
74,577,557
c++17: function template lambda specialization
Motivation: one has a function that accepts either a lambda or a value (for simplicity it can be either const char * or std::string) like following template <typename LambdaOrValue> void Function(LambdaOrValue &&lambda_or_value) { // The idea here is to have sort of a magic that // evaluates a lambda if an argument is actually // a lambda or do nothing otherwise if (Evaluate(std::forward<LabmdaOrValue>(lambda_or_value)) == std::string("pattern")) // Do something } I'm struggling to properly implement a function Evaluate() i.e. to make the code below compile. In particular, which return value to use in the "value"-based implementation to preserve the type (e.g. const char * or std::string) #include <type_traits> #include <iostream> template <typename T> decltype(std::declval<T>()()) Evaluate(T &&t) { return t(); } template <typename T> T Evaluate(T &&t) { // <<--- What return type use here to preserve the type return std::forward<T>(t); } int main() { std::cout << Evaluate("test") << std::endl; std::cout << Evaluate([]() { return "lambda"; }) << std::endl; }
Since you have access to C++17, why not use std::is_invocable, if constexpr and decltype(auto) combo? template <typename T> auto Evaluate(T &&t) -> decltype(auto){ if constexpr (std::is_invocable_v<T>) return t(); else return std::forward<T>(t); }
74,578,188
74,578,940
Can't get rid of memory leak in c++
I'm trying to dynamically increase the capacity of an array but I keep getting memory leaks when running with valgrind. This is the code I'm running(nothing wrong with it shouldn't be the problem): //My struct struct ArrayList{ int size; //amount of items in a array int capacity; //the capacity of an array int* items; //the array itself }; //Dynamically create an array ArrayList* createList(int m){ ArrayList* n = new ArrayList; n->size = 0; n->capacity = m; n->items = new int[n->capacity]; return n ; } //Destroy an array void destroyList(ArrayList* List){ delete[] List->items; delete List; } The code to double the capacity(Where I get the memory leak): // double the capacity of an array by dynamically creating a new one and transfering the old values to it void doubleCapacity(ArrayList* List){ // save everything int saved_size = List->size; int saved_capacity = List->capacity; int* saved_items = new int[List->size]; for (int i = 0 ; i < List->size;i++){ saved_items[i] = List->items[i]; } // load everything destroyList(List); List->size = saved_size; List->capacity = saved_capacity*2; List->items = new int[List->capacity]; for (int i = 0; i < List->size; i++){ List->items[i] = saved_items[i]; } delete[] saved_items; } My main that tests the code for doublecapacity. int main() { // Run tests ArrayList* l = createList(4); l->size++; l->items[0] = 1; cout << l->size << endl; cout << l->capacity << endl; cout << l->items[0] << endl; doubleCapacity(l); cout << l->size << endl; cout << l->capacity << endl; cout << l->items[0] << endl; destroyList(l); return 0; }
Your doubleCapacity() function is implemented all wrong. It is creating a temporary array of the original size just to save a redundant copy of the current items. Then it creates a new array of the desired capacity and copies the temporary items into it. You don't need that temporary array at all, you can copy the original items directly into the final array. More importantly, you are destroying the ArrayList object itself, so any access to its members after it has been destroyed is undefined behavior. Try something more like this instead: void doubleCapacity(ArrayList* List){ if (List->capacity > (std::numeric_limits<int>::max() / 2)) throw std::overflow_error("capacity is too high to double"); int new_capacity = List->capacity * 2; int* new_items = new int[new_capacity]; for (int i = 0; i < List->size; i++){ new_items[i] = List->items[i]; } delete[] List->Items; List->items = new_items; List->capacity = new_capacity; }
74,578,963
74,579,020
Why can't constructors/destructors have alias names in C++?
Take this class: class Foo { public: using MyType = Foo; MyType* m = nullptr; //ok MyType* functor() { //ok return nullptr; } MyType() = default; //error ~MyType() = default; //error }; Why can you use alias names for members, but not for constructors or destructors?
m is a pointer to an instance of a type, which is aliased. OK. functor() returns a pointer to an instance of a type, which is aliased. OK. But a constructor/destructor is not itself a type, so you can't use a type alias for them. They must be named after the type they belong to. That is just the way the syntax works