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
70,755,986
70,756,027
Why is character array processed as true by if statement?
I tried the code given below and found that it actually prints "yes", which means that the character array is taken as true in if statement. But i wonder what is the reason. I mean its an array so did it returned the whole "string". Or it returned its first element that is "s", or it returned its memory location which is processed as true as anything other than 0 is true. char a[] = "string"; if (a) { printf("yes"); }
if (a) In this context, a reference to an array decays to a pointer to the first value of the array. The same thing would happen if a were to get passed as a function parameter. So, here, a is just a pointer. And since it's not a null pointer this always evaluates to true. char a[6] = "string"; This is not really relevant, but this literal string has seven characters, not six, by the way. You forgot about the trailing \0.
70,756,433
70,756,662
Can I assign and return without a utility routine?
Is there a way to "assign and return" without creating a utility routine? Here's my code: static int& do_work_(const int* p, int& result) { result = (*p) * 10; return result; } template<typename T> T& assign(const T* p, T& result) { result = *p; return result; } int& do_work(const int* p, bool cond, int& result) { return cond ? do_work_(p, result) : assign(p, result); } Can I implement do_work() without the assign() utility? The reason for the do_work() signature is that it's a nice convenience: const int value=1; int i, j; if (do_work(&value, true, i) == do_work(&value, false, j)) {}
If you want to return the result of an assignment operation you can (in most cases) do so without a 'utility' function like your assign, because the assignment expression itself has a value; from cppreference (bolding mine): The direct assignment operator expects a modifiable lvalue as its left operand and an rvalue expression or a braced-init-list (since C++11) as its right operand, and returns an lvalue identifying the left operand after modification. Or, from this Draft C++17 Standard: 8.5.18 Assignment and compound assignment operators       [expr.ass] 1   The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand; their result is an lvalue referring to the left operand. … Thus, as suggested in the comments, you can simply have the following: int& do_work(const int* p, bool cond, int& result) { return cond ? do_work_(p, result) : (result = *p); }
70,756,996
70,757,224
Default parameter in a function wouldnt compile/link without static inline
i was writing a BST class in C++ and wanted to add a default parameter to a function but, when i tried to the visual studio compiler gave compile and linking errors, so after a bit of googling, i made the root variable static inline and it worked, i want to know what does static inline change in this specific situation. here's the BST class code: #pragma once template<typename T> class BST { template<typename T> struct node { T data; node<T>* left; node<T>* right; node(T d) { data = d; left = right = nullptr; } }; public: BST() { root = nullptr; } ~BST() { delete root; } node<T>* insert(T d) { if (root == nullptr) { root = new node<T>(d); return root; } node<T>* current = root; node<T>* k = nullptr; while (current != nullptr) { k = current; if (current->data > d) { current = current->left; } else if (current->data < d) { current = current->right; } } if (k->data > d) { k->left = new node<T>(d); } else if (k->data < d) { k->right = new node<T>(d); } return root; } bool find(T d) { if (root == nullptr) { std::cerr << "Tree is empty! : "; return false; } node<T>* current = root; node<T>* k = nullptr; while (current->data != d) { k = current; if (current->left == nullptr || current->right == nullptr && current->data != d) { std::cout << "Not Found! : "; return false; } if (current->data > d) { current = current->left; } else if (current->data < d) { current = current->right; } } return true; } node<T>* findmax() { node<T>* temp = root; while (temp->right != nullptr) { temp = temp->right; } return temp; } node<T>* findmin(node<T>* temp = root) { while (temp->left != nullptr) { temp = temp->left; } return temp; } private: static inline node<T>* root; };
This is because The keyword this shall not be used in a default argument of a member function and non static member of a class is bound to this (i.e. root is equivalent to this->root). More about default parameters restrictions here. In your case you could have the following workaround: node<T>* findmin(node<T>* temp = nullptr) { if (temp == nullptr) temp = root; however I am not sure if you should use it, for the sake of clarity.
70,757,091
70,757,150
Why does my code do not run the switch statement? (Linked List)
I am a beginner and still learning how to use a switch statement. My professor asked us to make a linked list using a switch statement. I don't really know why the switch statement is not working as intended to be. Hoping someone can help me. OUTPUT The output of the program should look like this Menu [1] Inserting value in the link [2] Deleting value in the link [3] Exit Enter your choice: (Input) Inserting/Deleting a value at [a] Beginning [b] Middle [c] End [d] Exit Enter your choice: (Input) Input the value to be inserted/deleted: (Input) The values in the link are: (Output) CODE Here is the code that I'm working with #include <iostream> #include <malloc.h> #include <conio.h> #define getch() _getch() using namespace std; struct dlinklist { struct dlinklist* left; int data; struct dlinklist* right; }; typedef struct dlinklist node; node* start = NULL; node* getnode() { node* newnode; newnode = (node*)malloc(sizeof(node)); cout << "\n Input the value to be inserted: "; cin >> newnode->data; newnode->left = NULL; newnode->right = NULL; return newnode; } int menu() { char ah; int ch; cout << "\n----------------------------------"; cout << "\nMenu"; cout << "\n----------------------------------"; cout << "\n[1] Inserting value in the link"; cout << "\n[2] Deleting value in the link"; cout << "\n[3] Exit"; cout << "\n----------------------------------"; cout << "\n\n Enter your choice: "; cin >> ch; if (ch == 1) { cout << "\n----------------------------------"; cout << "\n Inserting a value at:"; cout << "\n[a] The Beginning of the list"; cout << "\n[b] The middle of the list"; cout << "\n[c] The end of the list"; cout << "\n[d] Exit"; cout << "\n----------------------------------"; cout << "\n\n Enter your choice: "; cin >> ah; } else if (ch == 2) { cout << "\n----------------------------------"; cout << "\n Deleting a value at:"; cout << "\n[a] The Beginning of the list"; cout << "\n[b] The middle of the list"; cout << "\n[c] The end of the list"; cout << "\n[d] Exit"; cout << "\n----------------------------------"; cout << "\n\n Enter your choice: "; cin >> ah; } else if (ch == 3) { exit(0); } } void insert_beg() { //code } void insert_end() { //code } void insert_mid() { //code } void delete_beg() { //code } void delete_end() { //code } void delete_mid() { //code } void main(void) { int ch = menu(); char ah; while(1) { ah = menu(); switch(ah) { case 'A': case 'a': if (ch == 1) { insert_beg(); break; } else { delete_beg(); break; } case 'B': case 'b': if (ch == 1) { insert_mid(); break; } else { delete_mid(); break; } case 'C': case 'c': if (ch == 1) { insert_end(); break; } else { delete_end(); break; } case 'D': case 'd': exit(0); } } return; }
menu does not return any value. You probably want to do this: int menu() { char ah; int ch; cout << "\n----------------------------------"; cout << "\nMenu"; cout << "\n----------------------------------"; cout << "\n[1] Inserting value in the link"; cout << "\n[2] Deleting value in the link"; cout << "\n[3] Exit"; cout << "\n----------------------------------"; cout << "\n\n Enter your choice: "; cin >> ch; if (ch == 1) { cout << "\n----------------------------------"; cout << "\n Inserting a value at:"; cout << "\n[a] The Beginning of the list"; cout << "\n[b] The middle of the list"; cout << "\n[c] The end of the list"; cout << "\n[d] Exit"; cout << "\n----------------------------------"; cout << "\n\n Enter your choice: "; cin >> ah; return ah; // return statement } else if (ch == 2) { cout << "\n----------------------------------"; cout << "\n Deleting a value at:"; cout << "\n[a] The Beginning of the list"; cout << "\n[b] The middle of the list"; cout << "\n[c] The end of the list"; cout << "\n[d] Exit"; cout << "\n----------------------------------"; cout << "\n\n Enter your choice: "; cin >> ah; return ah; // return statement } else if (ch == 3) { // exit(0); don't write this here, call the exit inside main() return 3; // 3 or anything, you can return other values if you want } } And in main: int ch = menu(); if (ch == 3) exit(0); Don't forget about return statements when writing functions. Important note: Do not use ambiguous names for variables/functions/classes etc. For example, what does ah or ch really mean? How people reading your cryptic code are supposed to know that? Always try to use descriptive names.
70,757,795
70,757,959
Why does rvalue object does not get moved to function with rvalue parameter?
I was wondering why std::move to a function with an rvalue parameter was not actually moving anything, but passing by reference instead? Especially when I know it works for constructors. I was running the following code: #include <memory> #include <iostream> void consume_ptr(std::shared_ptr<int> && ptr) { std::cout << "Consumed " << (void*) ptr.get() << std::endl; } int main(int argc, char ** argv) { std::shared_ptr<int> ptr = std::make_shared<int>(); consume_ptr(std::move(ptr)); if (ptr) { std::cout << "ptr should be moved?" << std::endl; } return 0; } The output is: ptr should be moved? According to everything I've read, the std::shared_ptr should have been moved inside the function, meaning that the object ptr itself would hold nullptr after moving it into consume_ptr, but it doesn't! I tried it with some custom class of mine with logging, and it looks like the move constructor is never even called. It's reproducible under every compiler and optimization level. Can anyone clear this up for me please?
std::move by itself does not actually move anything. That is to say, std::move alone does not invoke any move constructors or move-assignment operators. What it actually does is effectively cast its argument into an rvalue as if by static_cast<typename std::remove_reference<T>::type&&>(t), according to cppreference. In order for any moving to actually happen, the moved object must be assigned to or used in the move-initialization of something else. For example, it could be used to initialize a member. void something::consume_ptr(std::shared_ptr<int> && ptr) { this->ptr = std::move(ptr); std::cout << "Consumed " << (void*) ptr.get() << std::endl; } However, one way to make your pointer get moved without being assigned to anything is to simply pass it by value, causing your pointer to be moved into the parameter. void consume_ptr(std::shared_ptr<int> ptr) { std::cout << "Consumed " << (void*) ptr.get() << std::endl; } This way can actually be more useful than the rvalue way if you're going to end up assigning the parameter to something, because it allows you to pass stuff in by copy, too, and not just by move. void consume_ptr_by_rvalue(std::shared_ptr<int> && ptr); void consume_ptr_by_value(std::shared_ptr<int> ptr); void do_stuff() { std::shared_ptr<int> x = /*...*/; std::shared_ptr<int> y = /*...*/; // consume_ptr_by_rvalue(x); // Doesn't work consume_ptr_by_rvalue(std::move(y)); // Risk of use-after-move std::shared_ptr<int> z = /*...*/; std::shared_ptr<int> w = /*...*/; consume_ptr_by_value(z); consume_ptr_by_value(std::move(w)); // Still risk, but you get the idea consume_ptr_by_value(make_shared_ptr_to_something()); // Can directly pass result of something }
70,757,922
70,758,141
C++ copy assignment operator behaviour
I used the code below to test the behaviour of copy assignment operator: #include <iostream> using namespace std; int group_number = 10; // Global class Player { public: explicit Player(const int &g): group(g) { } Player& operator=(const Player& rhs) { cout << "Copy assignment operator called " << endl; return *this; } void set_stamina(int i) {stamina = i; } int get_stamina() {return stamina; } const int &get_group() const { return group; } protected: const int &group; private: int stamina; }; // End of Player class class Round { public: Round(const Player &p) { main_player = &p; } const Player &get_main_player() const { return *main_player; } protected: const Player *main_player; }; // End of Round class // Test code int main() { Player p1(group_number); Round r(p1); p1.set_stamina(100); // Add player2 in the same group as p1 Player p2(group_number); p2 = r.get_main_player(); cout << "This is p1's stamina: " << p1.get_stamina() << ", and p1's group number: " << p1.get_group() << endl;; cout << "This is p2's stamina: " << p2.get_stamina() << ", and p2's group number: " << p2.get_group() << endl;; return 0; } I expected both p1 and p2 have the same value of stamina. But the output shows that p2's stamina is different from p1's Copy assignment operator called This is p1's stamina: 100, and p1's group number: 10 This is p2's stamina: 241098768, and p2's group number: 10 Why the copy assignment operator not copying the value of p1's stamina to p2?
You have not copied the data member stamina inside the copy assignment operator. So just add stamina = rhs.stamina; inside the copy assignment operator and you'll get your expected output. So the modified definition of operator= looks like: Player& operator=(const Player& rhs) { cout << "Copy assignment operator called " << endl; stamina = rhs.stamina; //ADDED THIS return *this; } Also, note that in your original code snippet, since the data member stamina is not initilized and so it has indeterminate value. Using this uninitialized variable(which you do when you wrote p2.get_stamina();) is undefined behavior. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. So the output that you're seeing is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program. To solve this more serious problem just use in-class initilaizer for data member stamina. class Player { //other members here private: int stamina = 0; //USE IN-CLASS INITIALIZER }; 1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
70,758,414
70,758,709
How to find certain substring in string and then go back to certain character?
I save messages in string and I need to make filter function that finds user specified word in those messages. I've split each message by '\n' so the example of one chat would be: user1:Hey, man\nuser2:Hey\nuser1:What's up?\nuser2:Nothing, wbu?\n etc. Now user could ask to search for word up and I've implemented a search like this: for (auto it = msg.cbegin(); (it = std::find(it, msg.cend(), str)) != msg.cend(); it++) and I could put that string into stringstream and use getline to \n, but how do I go backwards to previous \n so I can get full message? Also, what about first message, cause it doesn't start with \n?
Since you said you split the strings, I image you have a vector of strings where you want to find up for example. You would do something like this for (const auto& my_string: vector_of_strings){ if (my_string.find("up") != string::npos) { // message containing up is my_string } } In case you haven't split the strings in a vector you can use this func inspired by this: vector<string> split(const string& s, const string& delimiter){ vector<string> ret; size_t last = 0; size_t next = 0; while ((next = s.find(delimiter, last)) != string::npos) { ret.emplace_back(s.substr (last, next - last)); last = next + 1; } ret.emplace_back(s.substr(last)); return ret; } If this function doesn't work you can always take a look at How do I iterate over the words of a string?
70,759,474
70,759,579
What would happen if I used a cout statement as the condition for an if statement?
So, my programming instructor asked me to try putting a cout-statement as the condition for an if-statement and see what happens. I tried it (just made a random code) and didn't notice anythimg special. Here's the code. #include<iostream> using namespace std; int main() { int x=1; int y=2022; if(cout<<"Covid") { cout << "\n Us \n"; x=y; cout << x; } } The output is simply Covid Us 2022 What I don't understand is why this would be used. From my amateur understanding, even if I used an else-statement or any amount of else-if statements, they wouldn't run, since the condition for the if-statement is self-fulfilling. I could the simply write the whole code directly without using an if-statement. What then, could be the purpose of using an if-statement? Any general use?
Prior to C++11, when you write if(cout << "Covid"), there is an implicit conversion to void*. This value is unspecified by the C++ standard, other than if the stream is in an error state, then nullptr is returned. From C++11, the implicit conversion is to bool. false denotes the stream is in an error state, true otherwise. Note that you must have imbued a very funky iostream-derived object indeed for the output to be "Pakistan" given your input!
70,759,629
70,759,671
Is there a type in the standard for storing the begin- and end-iterators of a container?
My question is really simple: Is there a type in the standard whose purpose is to store the begin-terator and the end-iterator for a container? I want to return both iterators from a single function. I'm aware I could use std::pair for this but it feels like there would be some type in the standard for this exact purpose. I've scanned the <iterator> header but can't seem to find a type like this. I'm not that good at iterator terminology so I'm not sure if one of those actually do what I'm looking for. Is there one that does? (If you're interested in why I even want to do it in the first place, I have constant arrays in a class template that derives from a base class. Using polymorphism I want to iterate over their class constants, but I obviously can't have the virtual functions of the base class return the actual arrays since those are templated. Hence, I have virtual functions returning plain pointers, called someArrayBegin(), someArrayEnd(), otherArrayBegin(), etc, that I override in the derived class template to return the correct addresses.)
Is there a type in the standard for storing the begin- and end-iterators of a container? Your description matches closely with the concept of a range. std::ranges::subrange can be created from a pair of iterators. That will be templated based on the iterator type. If you need to hide the iterator type for runtime polymorphism, you would need ranges::any_view which unfortunately isn't in the standard implementation of the ranges. Furthermore, there is a runtime cost associated with it. For contiguous containers, another alternative is std::span which can point to any contiguous range without the cost of type erasure. For strings in particular, yet another alternative is std::string_view.
70,760,036
70,761,803
How to develop a constexpr implementation of boost::pfr::for_each?
I am using boost::pfr and it's quite impressive the way it uses reflection without any neccesity of macro registering of variables. But the issue I wonder is why boost::pfr::for_each was not declared as constexpr, avoiding in current situation the use of PFR for_each within any constexpr function declared by users. Is there any way I can bypass this issue without changing original boost::pfr source code? EDIT: I include a working example and a link to coliru to show my point. https://coliru.stacked-crooked.com/a/443f8bd2ad66ca4c #include <iostream> #include "boost/pfr.hpp" struct Variable { }; struct Var1 : public Variable { static constexpr int size { 5 }; }; struct Var2 : public Variable { static constexpr int size { 10 }; }; struct Var3//This one does not depend of class Variable! { static constexpr int size { 20 }; }; struct Packet { Var1 var1; Var2 var2; Var3 var3; }; template<typename T> constexpr int accumulate(const T& ref) { int result{}; boost::pfr::for_each_field(ref, [&](auto& field) { if (std::is_base_of<Variable, std::decay_t<decltype(field)>>::value) result += field.size; }); return result; } int main() { Packet packet; /*constexpr*/ auto size = accumulate(packet);//constexpr must be commented! std::cout << size; //static_assert(size == 15);//It can not be used due to non-constexpr! }
This looks like an oversight in the implementation, given that it could easily be constexpr, at least for the C++17 implementation - godbolt example In the meantime you can build your own constexpr one using boost::pfr::structure_tie (which is constexpr) & std::apply: godbolt example template<class T, class F> constexpr void for_each_field(T&& obj, F&& func) { std::apply([f = std::forward<F>(func)](auto&&... elements) mutable { (std::forward<F>(f)(std::forward<decltype(elements)>(elements)), ...); }, boost::pfr::structure_tie(std::forward<T>(obj))); }
70,760,158
70,760,388
What is the definition of "single statement" in C++?
Identify a statement that is false for the given snippet: int n = 1 + 2; A. 1 and 2 are operands. B. + is operator. C. ; marks the end of a statement in C++. D. It is a single statement.
The answer is C. The grammar production for a for statement is for ( init-statement conditionopt ; expressionopt ) statement So, in for (int i = 0; i < 10; ++i) the first ; ends the "init-statement". The second ; is part of the for loop grammar, and does not end a statement.
70,760,458
70,760,634
Why do I keep getting this error: exception Unhandled : Unhandled exception thrown: read access violation. this was 0x4
I am currently working on the BlackJack project, but there is an error showing "exception Unhandled: Unhandled exception thrown: read access violation. this was 0x4.". I am not quite sure which part I did wrong, and the program sometimes runs normally sometimes shows that exception. In draw_card function, it returns a value of a random number. For example: if we get 13, the value will be 10. It also returns the name of the card and the type of the card such as 13 corresponds to king. int main() { srand(time(0)); unsigned bet; int player = 0 , dealer = 0; string card , type; cout << "You have $100. Enter bet: "; cin >> bet; cout << "Your cards are:" << endl; player += draw_card(card, type, player); cout << " "+card + " of " + type << endl; player += draw_card(card, type, player); cout << " " + card + " of " + type << endl << endl << endl; } int draw_card(string& card, string& type, int drawer_points) { int randomNumber; //between 1 and 13 int suite; //between 1 and 4 to determine the suite of the card. randomNumber = rand() % 13 + 1; suite = rand() % 4 + 1; card = getRank(randomNumber); type = getSuit(suite); if (randomNumber == 13 || randomNumber == 12 || randomNumber == 11) { return 10; }else if (randomNumber == 1) { int ace1 = 21 - (drawer_points + 1); int ace2 = 21 - (drawer_points + 11); return ace1 < ace2 ? 1 : 11; } else { return randomNumber; } } string getSuit(int suit) { switch (suit) { case 0: return "spades"; break; case 1: return "clubs"; break; case 2: return "diamonds"; break; case 3: return "hearts"; break; default: break; } } string getRank(int rank) { switch (rank) { case 13: return "King"; break; case 12: return "Queen"; break; case 11: return "Jack"; break; case 1: return "Ace"; break; case 2: return "Two"; break; case 3: return "Three"; break; case 4: return "Four"; break; case 5: return "Five"; break; case 6: return "Six"; break; case 7: return "Seven"; break; case 8: return "Eight"; break; case 9: return "Nine"; break; case 10: return "Ten"; break; default: break; }
You generate suite = rand() % 4 + 1; This is a random number between 1 and 4 inclusive. You then call getSuit(suite); But getSuit only has switch branches for values between 0 and 3 inclusive: switch (suit) { case 0: return "spades"; break; case 1: return "clubs"; break; case 2: return "diamonds"; break; case 3: return "hearts"; break; default: break; } Not returning a value from a function that is declared to return a value is undefined behaviour.
70,761,598
70,761,684
Target-typing in modern C++
When I say target-typing I mean using the type of the receiver variable or parameter as information to infer parts of the code I'm assigning to it. Like for example, in C# you'd write something like this to pass a nullable value or a null (empty) if necessary: void f(int? i) {} void caller(bool b) => f(b ? 5 : null); // value is bound to an int? parameter so all information // to build this object is already in code The best I could come up with in C++ is something like this: void f(const optional<int>& i) {} void caller(bool b) { f(b ? make_optional(5) : optional<int>()); } And it works, but it requires me to write optional twice and provide the optional type once, even though all the information should already be in code. This is, in my humble opinion, what type inference should do for you without having to repeat yourself multiple times per line. And because the following does work: optional<int> i; i = {}; // empty i = {5}; // a value I'd have thought that the next logical step would also work: void f(const optional<int>& i) {} void caller(bool b) { f(b ? {5} : {}); // doesn't compile } So overall from various experiments it seems target-typing works when directly assigning a value to a variable, but not as part of a ternary conditional expression bound to a parameter? Am I understanding this correctly? There is no limit on the C++ version, I've been writing this in MS C++20 for instance. And a related question, though not the main focus of my question, is there a better way of writing an optional<> initialization that can either have a value or not based on a boolean?
In C++, expressions have types. {} is not, however, an expression. There are a handful of restricted contexts where {} could be used when you'd expect an expression should go there. This doesn't make {} into an expression. ?: is an operation, and its arguments must have types. The type of ?: is derived from the type of its 2 arguments (the rules are complex, but it tries to find a common type). b ? std::optional{5} : std::nullopt; is similar to what you want. Here, the fact that std::nullopt can convert to a std::optional<int> is used to deduce the type of ?: expression. You can also write: template<class T> std::optional<std::decay_t<T>> maybe( bool b, T&& t ) { if (!b) return std::nullopt; return std::forward<T>(t); } which lets you write maybe( b, 5 ) for your case. Fancier things can be done, where you use template<class T> operator T() on a type to deduce the type you are returning into. But, in general, the C++ type system goes one way.
70,761,711
70,761,785
std::variant template deduction when isolating containing type
I have been making a serializer today and am having trouble getting it to work with variants. I have used this process before for various other things where I keep trimming off the type till I get to the one type I need. However, it seems VC++ can't deduce it this time. Here is a complete example of the error. #include <type_traits> #include <variant> #include <iostream> #include <sstream> void serialize( auto& s, float v ) { std::cout << "serialize float"; } void serialize( auto& s, int v ) { std::cout << "serialize int"; } void serialize( auto& s, bool v ) { std::cout << "serialize bool"; } namespace detail { template<typename VariantT, typename T1, typename ...Rest> void serialize_variant( auto& s, const VariantT& v ) { if ( std::holds_alternative<T1>( v ) ) return serialize( s, std::get<T1>( v ) ); else if ( sizeof...(Rest) >= 1 ) return serialize_variant<VariantT, Rest...>( s, v ); else return; } } template<typename ...VariantTs> void serialize( auto& s, const std::variant<VariantTs...>& v ) { detail::serialize_variant<std::variant<VariantTs...>, VariantTs...>( s, v ); } int main() { std::stringstream s{}; std::variant<float, int, bool> x = true; serialize( s, x ); } I am confused why this is not working. It should check to see if it T1 is the type the variant contains. If it is not then it checks if there are more types to check and calls the same serialize_variant function with one less type when there is, otherwise it just returns. It is throwing a no matching overload for serialize_variant on the recursive call and it says it cannot deduce T1. Can anyone shed some light on why this is failing to compile? It is the following errors I am getting Error C2672 'serialize_variant': no matching overloaded function found Error C2783 'void detail::serialize_variant(_T0 &,const VariantT &)': could not deduce template argument for 'T1' Thanks.
The branch with sizeof...(Rest) >= 1 must also be valid when the condition is false, but it isn't. You can get it discarded when the condition is false via if constexpr. Moreoever you were trying to return something but the return type is void. namespace detail { template<typename VariantT, typename T1, typename ...Rest> void serialize_variant( auto& s, const VariantT& v ) { if ( std::holds_alternative<T1>( v ) ) /*return*/ serialize( s, std::get<T1>( v ) ); else { if constexpr ( sizeof...(Rest) >= 1 ) /*return*/ serialize_variant<VariantT, Rest...>( s, v ); else return; } } } Complete example
70,762,310
70,806,752
I'm getting undefined reference to `i2c_smbus_read_word_data and 'extern "C"' doesn't fix it
I'm getting the error undefined reference to i2c_smbus_read_word_data(int, unsigned char)` I've tried wrapping a few of my libraries in extern "C" but I get the same error. I tried this after seeing this answer to a similar problem. Regardless of whether I wrap some or all of these include #include <linux/i2c-dev.h>, #include <i2c/smbus.h>, #include <linux/i2c.h>, #include <sys/ioctl.h> statements I get the same error. The error is i2c_read.cpp:(.text+0xf8): undefined reference to i2c_smbus_read_word_data(int, unsigned char)' collect2: error: ld returned 1 exit status` I am running my command $g++ i2c_read.cpp -li2c with -li2c as you can see. extern "C" { #include <linux/i2c-dev.h> #include <i2c/smbus.h> } #include <linux/i2c.h> #include <sys/ioctl.h> #include <fcntl.h> /* For O_RDWR */ #include <unistd.h> #include <iostream> using namespace std; int file; int adapter_nr = 2; char filename[20]; int main() { cout << filename << 19 << "/dev/i2c-1" << adapter_nr; file = open(filename, O_RDWR); if (file < 0) { exit(1); } int addr = 0x74; if (ioctl(file, I2C_SLAVE, addr) < 0) { exit(1); } __u8 reg = 0x40; __s32 res; char buf[10]; res = i2c_smbus_read_word_data(file, reg); if (res < 0) { /* ERROR HANDLING: i2c transaction failed */ } else { /* res contains the read word */ } buf[0] = reg; buf[1] = 0x42; buf[2] = 0x43; if (write(file, buf, 3) != 3) { /* ERROR HANDLING: i2c transaction failed */ } }
I did a sudo apt-get update and the problem went away. I also ran a few commands to update the compiler, though it still says my g++ version is 7.5, so that might have also contributed.
70,763,494
70,763,573
What are the downsides to accessing a std::map<std::string, int> using string literals?
I have written a ResourceManager class in C++ that contains a std::map<std::string, Resource>. My current code then accesses these methods using string literals, e.g: // ResourceManager.h class ResourceManager { private: std::map<std::string, Resource> public: void loadResource(std::string_view resourceName, std::string_view fileName); const Resource& getResource(std::string_view resourceName) const; } // a.cpp resourceManager.loadResource("background image", "background_image.png") // b.cpp resourceManager.getResource("background image") Is this going to be a problem? Should I replace all these string literals with constants defined in a constants.h file? In this case, should I just use an enum as the key to the map instead?
As with any other situation where magic constants are used, it can lead to brittle code, i.e., code that is likely to become broken. In particular, consider what happens if a "background image" resource is loaded once and retrieved from multiple different locations, possibly spanning many source files. If the resource is renamed in the loadResource call, but you forget to change one of the getResource calls, the program will have a bug. This issue can be avoided using an enum or using named constants. One additional benefit of having an enum as the key is that it's very efficient: any copies of the key that are made in the course of looking up the value are cheap. This stands in contrast to your current code, where you may be copying resourceName in order to perform a lookup (although this can be avoided using a transparent comparator).
70,763,549
70,772,972
ROS cpp callback without message type
I want to create a ROS node that is able to listen to a topic without knowing its message type. In python, this is possible as can be seen here: https://schulz-m.github.io/2016/07/18/rospy-subscribe-to-any-msg-type/ I tried that and it works like a charm. However, I want to avoid copying the whole message; thus, i need that functionality in a roscpp nodelet.
By nature, this sort of problem is very pythonic and much harder to work around in c++. That being said, there is one (sort of) solution out there already. Take a look at the ros_msg_parser. The syntax isn't pretty, and I'm not even sure if it's a good idea, but it will let you generate generic subscribers. Example from the linked repo: boost::function<void(const RosMsgParser::ShapeShifter::ConstPtr&)> callback; callback = [&parsers, topic_name](const RosMsgParser::ShapeShifter::ConstPtr& msg) -> void { topicCallback(*msg, topic_name, parsers); }; ros::Subscriber subscriber = nh.subscribe(topic_name, 10, callback);
70,764,818
70,765,683
member "Node::next" (of a friend class) is inaccessible
I am building my own LinkedList, because I need a special Node that holds more data. I specify that my Node class is a friend of the LinkedList class, but it doesn't seem to allow me to access the private variables in the Node class from the LinkedList class. Node.h class Node { private: Node* next; ... }; LinkedList.h #include "Node.h" class LinkedList { friend class Node; ... }; LinkedList.cpp ... void LinkedList::insertFirst(Node* n) { Node* temp = this->root; this->root = n; this->root->next = temp; // 1 } ... 1 This is where I get the error. It says that the this->root->next is inaccessible, but I have it as a friend class to my LinkedList and so private variables should be accessible to it. There are quite a few questions here on Stack Overflow that talk about something similar to my question, but none of them seem to be what I need. One answer was saying to switch from private to protected, but that didn't work, it just changed the error to say it can't access the protected member. Another answer was saying that they had a misspelling in there friend declaration. I checked mine, and it is spelled correctly. Another was saying to make sure that the classes are declared in the correct order, but since I have them in different files, and #include the file where I create the class that is declared as a friend. There were quite a few more that I looked at, but all were similar to the above mentioned and didn't help me solve my problem. What am I missing/not understanding? Nothing I've tried has worked, and I would really appreciate any help.
A friend declaration grants access of the specified class to the private members of the declaring class (ie, "that class X over there is a friend of mine, he has permission to use my private stuff"). So, by declaring Node as a friend inside of LinkedList, you are granting Node access to LinkedList's private members, not the other way around like you want. To let LinkedList access Node::next, you need to declare LinkedList as a friend of Node instead: class Node { friend class LinkedList; ... };
70,764,819
70,764,987
How can i find the integers that can be written as a sum of a power of 2, a power of 3 and a power of 5? C++
So the program must compute all the numbers that can be written as a sum of a power of 2, a power of 3 and a power of 5 below 5.000.000. For example 42 = 16 + 1 + 25 = 2^4 + 3^0 + 5^2. Any idea how can I do this?
you can get all powers of 2 and all powers of 3 and all powers of 5 under 5.000.000. first Then you can try all combinations vector<int> solve(){ const int M = 5000000; vector<int> p_2={1},p_3={1},p_5={1}; while(p_2.back()*2<M)p_2.push_back(p_2.back()*2); while(p_3.back()*3<M)p_3.push_back(p_3.back()*3); while(p_5.back()*5<M)p_5.push_back(p_5.back()*5); set<int> st;//to remove duplicates for(auto power_of_2 :p_2){ for(auto power_of_3:p_3){ for(auto power_of_5:p_5){ If(power_of_2+power_of_3+power_of_5<M) st.insert(power_of_2+power_of_3+power_of_5); } } } return vector<int>(st.begin(),st.end()); }
70,765,063
70,770,238
V8 Embedding. Cannot print out the `v8::Local` object
In Short I was trying to print out the v8::Local object content, with either of v8/tools/gdbinit and v8/tools/lldb_commands.py helper scripts, I got Empty Line OR Syntax Error messages. Is there anything I've missed? So my question is how can we print the v8::Local object content? Most of configurations are from official embed tutorial (https://v8.dev/docs/embed), without any single line of modification. Here are some details: Source Branch: "main" (2022/01/18) GN Build Configuration: "x64.release.sample" Program: v8/samples/hello-world.cc Platform: "Ubuntu18.04 + GDB10" / "macOS 10.14 + LLDB11" GDB ouput: (ubuntu18.04) ### Compile & Link $ g++ -I. -Iinclude samples/hello-world.cc -o hello_world -lv8_monolith -ldl -Lout.gn/x64.release.sample/obj/ -pthread -std=c++14 -DV8_COMPRESS_POINTERS -g ### Debug $ gdb -x tools/gdbinit ./hello_world (gdb) p result $1 = {val_ = 0x55d4f7a35408} (gdb) jlh result A syntax error in expression, near `)(result).val_))'. LLDB ouput: (macos10.14) ### Compile & Link $ g++ -I. -Iinclude samples/hello-world.cc -o hello_world -lv8_monolith -Lout.gn/x64.release.sample/obj/ -pthread -std=c++14 -DV8_COMPRESS_POINTERS -g ### Debug $ lldb ./hello_world (lldb) command script import tools/lldb_commands.py (lldb) b hello-world.cc:56 (lldb) r (lldb) p *utf8 (char *) $0 = 0x0000000102302590 "Hello, World!" (lldb) p result (v8::Local<v8::Value>) $1 = (val_ = 0x0000000102815668) (lldb) jlh result (lldb)
For debugging, try using a debug build: use gn args <your_output_dir> to set is_debug = true, then recompile. If you insist on debugging release-mode binaries, you can enable jlh and friends with the v8_enable_object_print = true GN arg, but your experience will likely be weird in other ways (e.g. stepping and breakpoints won't be reliable, many values will be <optimized out>, etc.).
70,765,272
70,766,140
Does std::format() accept different string types for format and arguments?
With printf I can do something like this wprintf(L"%hs", "abc"); where the format is wchar_t * but argument is char *. Is this doable with std::format(), or do I have to convert one to the other prior? When I do std::format(L"{:hs}", "abc"); I get compile error about type mismatch.
It cannot. As per the documentation, the format string matches Python’s format specification, which does not have any magic for directly dealing with different string types or encodings. (Python does everything behind the scenes with CESU-8, IIRC.) This is one of those things where I wish the C++ Standard would just Do The Right Thing™, but as the C++ Standards Committee still hasn’t hashed out how they want to handle string encoding transformations (as of Jan 2022) we are stuck with a dumb std::format. The ultimate goal, I think (and hope), is that std::format will one day accept different string types and transform them properly for you without having to change the fmt argument. For now, however, you must perform the transform yourself. Alas, ATM std::format will only accept like string types for all arguments, where the base character type is either char or wchar_t. That’s it. (More docs.)
70,765,285
70,765,307
How to use <stacktrace> in GCC trunk?
From https://github.com/gcc-mirror/gcc/commit/3acb929cc0beb79e6f4005eb22ee88b45e1cbc1d commit, C++ standard header <stacktrace> exists things such as std::stacktrace_entry but is not declared since _GLIBCXX_HAVE_STACKTRACE is not defined neither. I have tried this on https://godbolt.org/z/b9TvEMYnh but linker error is emitted once I have added the argument -lstd++_libbacktrace (ofc, it was not found) #include <stacktrace> // header found int main() { // can't use features like 'std::stacktrace_entry' and 'std::stacktrace' } What does this message mean from the commit description? : For now, the new library is only built if --enable-libstdcxx-backtrace=yes is used.
Part of building GCC from source is to run the configure shell script and pass it a bunch of arguments to tell it how to behave. That commit message is telling you that in order to enable this feature, you must add the following configure argument: --enable-libstdcxx-backtrace=yes
70,765,507
70,765,625
Initialize a std::vector of structures to zero
I am guaranteed to initialize a vector of struct with each element initialized to zero with that code ? #include <vector> struct A { int a, b; float f; }; int main() { // 100 A's initialized to zero (a=0, b=0, f=0.0) // std::vector<A> my_vector(100, {}); does not compile std::vector<A> my_vector(100, A{}); }
Yes it is guaranteed since A{} is value initialization and from cppreference: Zero initialization is performed in the following situations: As part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors, including value initialization of elements of aggregates for which no initializers are provided. You can also use: std::vector<A> my_vector(100, {0,0,0});
70,765,553
70,766,925
CUDA : Shared memory alignement in documentation
We can see on the official Nvidia website that to use multiple arrays of shared memory of unknow size, we can use that code in the kernel: __global__ void myKernel() { extern __shared__ int s[]; int *integerData = s; // nI ints float *floatData = (float*)&integerData[nI]; // nF floats char *charData = (char*)&floatData[nF]; // nC chars } // Kernel launch myKernel<<<gridSize, blockSize, nI*sizeof(int)+nF*sizeof(float)+nC*sizeof(char)>>>(...); However, we know that the memory should also be aligned. Isn't this code undefined behaviour if for example sizeof(float) == 8 and sizeof(int) == 4 ? This may be a convoluted size, but the problem is more apparent if we just put the char on top: __global__ void myKernel() { extern __shared__ char s[]; char *charData = s; // nC chars int *integerData = (int*)&s[nC]; // nI ints float *floatData = (float*)&integerData[nI]; // nF floats } If nC is not multiple of sizeof(int), the pointers are misaligned. So my question is, does this work for this specific example or should I worry about alignment ? And if yes, what is the common pattern or how to manage that in code ?
Yes, you have to worry about alignment. The easiest way to get around this is to sort arrays by alignment from largest to smallest, meaning double + long long -> float + int -> … Since all integral types have sizes and alignments that are powers of 2, you won't waste any space when you pack your arrays like that. Extra care needs to be taken around platform-specific types like size_t or wchar_t. Same goes with vector types. float3 has lower alignment than float2. In normal C++ code, we could use std::align to compute our pointers. But that doesn't work with CUDA, so we roll our own version if we need a generic solution. #include <cstdint> /** * in normal code we could use std::align but that doesn't work with CUDA * * Behavior is undefined if alignment is not a power of 2 * (same as everywhere else) * * \tparam T array element type * \param n_elements number of array entries * \param ptr in-out parameter. On entry, points at first usable location. * On exit, will point at first location after the end of the array * \param space if not null, the used space (including padding for alignment) * will be added to the value currently stored in here * \return properly aligned pointer to beginning of array */ template<class T> __host__ __device__ T* align_array(std::size_t n_elements, void*& ptr, std::size_t* space=nullptr) noexcept { const std::size_t alignment = alignof(T); const std::uintptr_t intptr = reinterpret_cast<uintptr_t>(ptr); const std::uintptr_t aligned = (intptr + alignment - 1) & -alignment; const std::uintptr_t end = aligned + n_elements * sizeof(T); if(space) *space += static_cast<std::size_t>(end - intptr); ptr = reinterpret_cast<void*>(end); return reinterpret_cast<T*>(aligned); } __global__ void myKernel(int nI, int nF, int nC) { extern __shared__ char s[]; void* sptr = s; volatile char* charData = align_array<char>(nC, sptr); volatile int* integerData = align_array<int>(nI, sptr); volatile float* floatData = align_array<float>(nF, sptr); floatData[0] = charData[0] + integerData[0]; } void callKernel(int nI, int nF, int nC) { std::size_t shared_size = 0; void* sptr = nullptr; align_array<char>(nC, sptr, &shared_size); align_array<int>(nI, sptr, &shared_size); align_array<float>(nF, sptr, &shared_size); myKernel<<<gridsize, blocksize, sharedsize>>>(nI, nF, nC); }
70,765,743
70,781,619
Return multiple mock objects from a mocked factory function which returns std::unique_ptr
How to return multiple mock objects from a mocked factory function which returns std::unique_ptr? Return(ByMove(...)) cannot be used to return multiple times. Trying to work from this answer: https://stackoverflow.com/a/70751684/3545094 I came up with this: class MyType { public: virtual ~MyType() {} }; class MyTypeMock : public MyType {}; class MyFactory { public: virtual ~MyFactory() {} virtual std::unique_ptr<MyType> create() = 0; }; class MyFactoryMock : public MyFactory { public: MOCK_METHOD0(create, std::unique_ptr<MyType>()); }; TEST(SomeTest, MyTestCase) { MyFactoryMock myFactoryMock; EXPECT_CALL(myFactoryMock, create()) .Times(3) .WillRepeatedly([]() { return std::make_unique<MyTypeMock>(); }); (void)myFactoryMock.create(); (void)myFactoryMock.create(); (void)myFactoryMock.create(); } Problem is conversion from lambda to Action it seems: /.../my_test.cc: In member function ‘virtual void SomeTest_MyTestCase_Test::TestBody()’: /.../my_test.cc:122:111: error: cannot convert ‘SomeTest_MyTestCase_Test::TestBody()::<lambda()>’ to ‘const testing::Action<std::unique_ptr<MyType>()>&’ 122 | EXPECT_CALL(myFactoryMock, create()).Times(3).WillRepeatedly([]() { return std::make_unique<MyTypeMock>(); }); | ^ In file included from /.../googletest/1.8.0-57/include/gmock/gmock-generated-function-mockers.h:43, from /.../googletest/1.8.0-57/include/gmock/gmock.h:61, from /.../my_test.h:15, from /.../my_test.cc:12: /.../googletest/1.8.0-57/include/gmock/gmock-spec-builders.h:1008:53: note: initializing argument 1 of ‘testing::internal::TypedExpectation<F>& testing::internal::TypedExpectation<F>::WillRepeatedly(const testing::Action<F>&) [with F = std::unique_ptr<MyType>()]’ 1008 | TypedExpectation& WillRepeatedly(const Action<F>& action) { | ~~~~~~~~~~~~~~~~~^~~~~~ What am I missing?
Stepping gtest/gmock to 1.10 solves this issue.
70,766,319
70,766,404
Get the total number of prime numbers from 1 to 1million
Env: Microsoft Visual Studio. Project type: Run code in a Windows terminal. Print "Hello World" by default. Running ok while get the total number of prime number from 2 to 100000. While not able to get the total number of prime number from 2 to 1000000. It will just return Hello World! Hello World from function(). The following is full code. #include <iostream> using namespace std; //c++ program execute from top to buttom. void function(); bool isPrimeNumber(int number) { for (int i = 2; i < number; i++) { if (number % i == 0) { return false; } } return true; } int main() { cout << "Hello World!\n"; function(); int c = 0; for (int i = 2; i < 100001; i++) { bool isPrime = isPrimeNumber(i); if (isPrime) { c++; } } cout << c << " is the total number of prime numbers \n"; system("pause>0"); } void function() { cout << "Hello World from function().\n"; }
Your program is probably hanging due too long timeout. As suggested in comments by @NathanPierson it is enough to check primality until i * i <= number which will speedup code greatly. As commented by @Quimby if you use GCC or CLang compiler then it is worth adding -O3 command line compile option, which does all possible optimizations to make code as fast as possible. For MSVC compiler you may use /GL /O2 options. Full corrected working code: Try it online! #include <iostream> using namespace std; //c++ program execute from top to buttom. void function(); bool isPrimeNumber(int number) { for (int i = 2; i * i <= number; i++) { if (number % i == 0) { return false; } } return true; } int main() { cout << "Hello World!\n"; function(); int c = 0; for (int i = 2; i <= 1000000; i++) { bool isPrime = isPrimeNumber(i); if (isPrime) { c++; } } cout << c << " is the total number of prime numbers \n"; system("pause>0"); } void function() { cout << "Hello World from function().\n"; } Output: Hello World! Hello World from function(). 78498 is the total number of prime numbers It is possible to implement Sieve of Erathosthenes, which is much more faster for multiple-number primality checking, than Trial-Division checking of each individual number. Sieve was also suggested by @PepijinKramer. Below is my implementation from scratch of Sieve of Erathosthenes for Prime Counting Function. I did time comparison of your prime counting function (based on Trial Division) and my (based on Sieve). And figured that for N of 10 000 000 sieved version is 128x times faster! Also did small optimization to your isPrimeNumber() function by trying only odd divisors in a loop (see i += 2). This way function doubles its speed. Try it online! #include <iostream> #include <vector> #include <chrono> bool isPrimeNumber(int number) { if (number <= 2) return number == 2; if ((number & 1) == 0) return false; for (int i = 3; i * i <= number; i += 2) if (number % i == 0) return false; return true; } int PrimeCountA(int last) { int c = 0; for (int i = 2; i <= last; ++i) if (isPrimeNumber(i)) ++c; return c; } int PrimeCountB(int last) { std::vector<bool> is_composite(last + 1); int c = 0, i = 0; for (i = 2; i * i < is_composite.size(); ++i) if (!is_composite[i]) { for (int j = i * i; j < is_composite.size(); j += i) is_composite[j] = true; ++c; } for (; i < is_composite.size(); ++i) if (!is_composite[i]) ++c; return c; } int main() { int const n = 10000000; auto const gtb = std::chrono::high_resolution_clock::now(); auto Time = [&]{ return std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - gtb).count() / 1000.0; }; double tb = 0; { tb = Time(); std::cout << "PrimeCountA " << PrimeCountA(n) << ", time " << (Time() - tb) << " sec" << std::endl; } { tb = Time(); std::cout << "PrimeCountB " << PrimeCountB(n) << ", time " << (Time() - tb) << " sec" << std::endl; } } Output: PrimeCountA 664579, time 4.223 sec PrimeCountB 664579, time 0.033 sec
70,766,398
70,766,758
C++ judgment conditional formatting question
#include <iostream> using namespace std; int foo(int x,int n); int main() { string s = "hello"; int k = 0; if((k - s.size()) < 0) { cout << "yes1"; } int temp = k - s.size(); if((temp) < 0) { cout << "yes2"; } } Anyone can tell me why the output is yes2? Where is the yes1????
If you look at if((k-s.size())<0), there was no type casting datatype. When you write int temp = k-s.size();, integer datatype convert result as integer value(-5). Then your result "yes2". Change k-s.size() to int(k-s.size()), you will get "yes1" and also "yes2".
70,766,614
70,766,732
C++ - Why does aggregate initialization not work with template struct
This code works, without having to specify a constructor: struct Foo { int a; int b; }; //... int a1, b1; Foo foo = {a1, b1}; If I make Foo a template, it doesn't work. template<typename T1, typename T2> struct Foo { T1 a; T2 b; }; //... int a1, b1; Foo foo = {a1, b1}; It says deduction failed / 2 arguments were provided while 1 expected. If I add a constructor like Foo(T1, T2){} then it works. I thought, that sort of construction just works by default for structs. What am I getting wrong? EDIT: I'm using Clang, which seems not to support it. Both MSVC and GCC compile it with c++20 compiler flag.
Since C++20 aggregates have implicitly-generated deduction guide so class template argument deduction works for aggregates too. int a1, b1; Foo foo = {a1, b1}; // works since C++20; T1 and T2 are deduced as int Before C++20, you need to add user-defined deduction guide, e.g. template<typename T1, typename T2> struct Foo { T1 a; T2 b; }; template<class T1, class T2> Foo(T1 a, T2 b) -> Foo<T1, T2>; Clang has not supported class template argument deduction for aggregates yet.
70,766,639
70,766,703
opengl window initialization issue
I'm trying to encapsulate GLFW in a class to make my code cleaner. So in my class, I've made the basic window creation but when I execute the program, it always enter in the if statement where I check if the initialization went right or not and I don't know why. This is what I have #include "include/Window.h" #include <iostream> Window::Window(int x, int y) { _window = glfwCreateWindow(x, y, "Heightmap Visualizer", NULL, NULL); } Window::~Window() { glfwTerminate(); } int Window::createWindow() { if (!_window) { std::cerr << "went here" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(_window); run(); glfwTerminate(); return 0; } void Window::run() { while (!glfwWindowShouldClose(_window)) { glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(_window); glfwPollEvents(); } } This is the header file #include <GLFW/glfw3.h> class Window { public: Window(int x, int y); ~Window(); int createWindow(); void run(); private: GLFWwindow* _window; };
Make sure to glfwInit(). Also good luck in your jorney learning GL and C++!
70,766,824
70,767,015
How I can run two threads parallelly one by one?
In C++ how i can write two parallel threads which will work one by one.For example in below code it need to print 0 t 100 sequentially.In below code the numbers are printing ,but all are not sequential.I need to print like 1,2,3,4,5,6.....99.If any body know , try to add with sample code also. #pragma once #include <mutex> #include <iostream> #include <vector> #include <thread> #include <condition_variable> using namespace std; class CuncurrentThread { public: mutex mtx; condition_variable cv; static bool ready; static bool processed; void procThread1() { for (int i = 0; i < 100; i += 2) { unique_lock<mutex> lk(mtx); cv.notify_one(); if(lk.owns_lock()) cv.wait(lk); cout << "procThread1 : " << i << "\n"; lk.unlock(); cv.notify_one(); } }; void procThread2() { for (int i = 1; i < 100; i += 2) { unique_lock<mutex> lk(mtx); cv.notify_one(); if (lk.owns_lock()) cv.wait(lk); cout << "procThread2 : " << i << "\n"; lk.unlock(); cv.notify_one(); } }; static void ThreadDriver(CuncurrentThread* thr) { vector<thread> threads; threads.push_back(thread(&CuncurrentThread::procThread1, thr)); threads.push_back(thread(&CuncurrentThread::procThread2, thr)); for (auto& thread : threads) thread.join(); }; }; bool CuncurrentThread::ready = false; int main() { CuncurrentThread tr; CuncurrentThread::ThreadDriver(&tr); }
You can use ready variable as a condition for condition variable. #include <mutex> #include <iostream> #include <vector> #include <thread> #include <condition_variable> using namespace std; class CuncurrentThread { public: mutex mtx; condition_variable cv; static bool ready; //static bool processed; void procThread1() { for (int i = 0; i < 100; i += 2) { unique_lock<mutex> lk(mtx); // cv.notify_one(); // if(lk.owns_lock()) // wait until this condition is true i.e. until ready is false cv.wait(lk, [&]() { return !ready; }); cout << "procThread1 : " << i << "\n"; // set ready to true and notify waiting thread ready = true; lk.unlock(); cv.notify_one(); } }; void procThread2() { for (int i = 1; i < 100; i += 2) { unique_lock<mutex> lk(mtx); // cv.notify_one(); // if (lk.owns_lock()) // wait until this condition is true i.e. until ready is true cv.wait(lk, [&]() { return ready; }); cout << "procThread2 : " << i << "\n"; // set ready to false and notify waiting thread ready = false; lk.unlock(); cv.notify_one(); } }; static void ThreadDriver(CuncurrentThread* thr) { vector<thread> threads; threads.push_back(thread(&CuncurrentThread::procThread1, thr)); threads.push_back(thread(&CuncurrentThread::procThread2, thr)); for (auto& thread : threads) thread.join(); }; }; bool CuncurrentThread::ready = false; int main() { CuncurrentThread tr; CuncurrentThread::ThreadDriver(&tr); } Link where I tested this: https://godbolt.org/z/4jEns16oq
70,767,210
70,767,557
How to solve undefined reference in main function?
Below is my header file , which declares the function set_params #ifndef PID_H #define PID_H class PID { float _kp,_ki,_kd,_error,_previous_error,_dt; public: void set_params(float kp, float ki, float kd,float error,float previous_error,float dt); }; #endif The following is my pid.cpp, it contains function definition. #include "PID.h" void PID::set_params(float kp, float ki, float kd,float error,float previous_error,float dt) { _kp = kp; _ki = ki; _kd = kd; _error = error; _previous_error = previous_error; _dt = dt; } The following is my main.cpp . I am using platformio in visual studio code PID pid; void setup() { // } void loop() { pid.set_params(3.0,0.05,2.05,0.5,0.0,1.0); } I get the error as follows It states that set_params is an undefined reference. I compile it by clicking this button marked with red, in reality I do not know how to compile thej pid.cpp file separately. If there is any way please provide me a link. Please tell me where I am mistaken. Thanking you
After you comment, even if including the cpp files is a workaround, please do not do that! You have two acceptable ways. define the method in the class itself in the include file Some IDE by default create an include file containing only the method declarations and put the definitions in an implementation cpp file. But the standard allow the definition to be inside the class definition, it is commonly used for small methods or templates (*) So your header could be: #ifndef PID_H #define PID_H class PID { float _kp,_ki,_kd,_error,_previous_error,_dt; public: void set_params(float kp, float ki, float kd,float error,float previous_error,float dt) { _kp = kp; _ki = ki; _kd = kd; _error = error; _previous_error = previous_error; _dt = dt; } }; #endif add the pid.cpp file to the list of source files for your project. This part actually depends on your build tools. But your screenshot shows that you already compile app.cpp and main.cpp. You just have to process pid.cpp the same way. For templates, the recommended way is to put all the implementation in the include file. Not doing so requires to consistently explicitely instanciate the template for all its future usages, which is not an option in a general library.
70,768,157
70,768,389
Variable is not a type
#include<iostream> #include<string> #include<vector> using namespace std; class Course { public: string name; string instructorInCharge; int numberOfStudents; int totalMarks; Course(string u, string v, int p, int q){ this->name=u; this->instructorInCharge=v; this->numberOfStudents=p; this->totalMarks=q; } vector<int> studentMarks (numberOfStudents); }; class Labs:public Course { vector<int>labMarks(numberOfStudents); }; int main() { Course c("Rahul","Hota",200,300); cout<<"hello there"; } When I compile this code I’m getting the following error: 1.cpp:20:31: error: 'numberOfStudents' is not a type 20 | vector<int> studentMarks (numberOfStudents); | ^~~~~~~~~~~~~~~~ 1.cpp:28:29: error: 'numberOfStudents' is not a type 28 | vector<int>labMarks(numberOfStudents); | ^~~~~~~~~~~~~~~~ Please tell me what my mistake is. numberostudents was supposed to be the size of the vector. But not any function.
If you want in-class initialization, you may do this: vector<int> studentMarks = vector<int>(numberOfStudents); Now the default constructor will initialize studentMarks with vector<int>(numberOfStudents) when an instance of Course is created. However, this will cause undefined behavior since numberOfStudents is not initialized before the initialization of studentMarks. You could use the member initalizer list instead: Course(std::string u, std::string v, int p, int q) : name(std::move(u)), instructorInCharge(std::move(v)), numberOfStudents(p), totalMarks(q), studentMarks(numberOfStudents) { } and likewise for the Labs class: class Labs : public Course { public: Labs(std::string u, std::string v, int p, int q) : Course(u, v, p, q), // initialize the base class part of a `Labs` labMarks(p) // initialize the added member variable { } std::vector<int> labMarks; };
70,768,599
70,768,679
Pointer to an unspecified variable
The following code gets compiled int v[] = { 0,1,2,3,4,5,6,7,8,9 }; std::cout << v[10] << std::endl; int x; int* ptr = &x; std::cout << *ptr << std::endl; I would like to understand why it was possible to display v[10] and *ptr and also why v[10] and *ptr have the same value. Could you please provide an explanation?
It is undefined behavior but for some of compilers it is how the variables are places in memory. In C/C++ you have direct access to memory (as a huge space with some addressation). x is just placed just after v[]. v[10] means 10th object from start (v is pointing to beginning). If it exceeds the size of container, it will try to decode what is stored at this address. In your case, there is stored variable x This undefined behavior is very often used to make attacks called "BufferOverflow" so you can search for it and see how it can be used to alter behavior of some applications :)
70,769,044
70,771,086
How to build cv::Mat from coloured rectangles
My goal is to create yield maps using OpenCV. These yield maps need to be built with coloured rectangles to indicate yield. An example of a Mat built by rectangles here. So is it possible to create a cv::Mat with coloured rectangles? The amount of rectangles isn't constant, thus changes with every use. To make the question clear: if I have 4 boxes (2x2 grid) I want to automatically make a Mat which is as big as the 4 boxes. If I have 16 boxes (4x4 grid) I want to make a Mat which is as big as the 16 boxes. I couldn't find a way to make it work, so I hope somebody here knows if it is possible. If somebody can help me that would be great, if it is not possible alternatives are also welcome! Thanks Some info: OpenCV version:4.5.3 OS: Ubuntu 20.04 Language: C++
OpenCV has cv::hconcat and cv::vconcat. Use them like numpy's hstack/vstack. make sure your parts have the same type (and number of channels). The documentation has a code example. cv::Mat matArray[] = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)), cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)), cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),}; cv::Mat out; cv::hconcat( matArray, 3, out ); //out: //[1, 2, 3; // 1, 2, 3; // 1, 2, 3; // 1, 2, 3]
70,769,192
70,776,764
Error using Thrust Zip iterator with device functor
I'm working in a Linux environnement with Cuda and Thrust I got a standard code and i need to transform it Because of this i try to use use zip_iterator for the first time and i have some issues with it. error: function "gridTransform::operator()" cannot be called with the given argument list Does someone know how to resolve this issues . Thanks thrust::host_vector<float> X_h; thrust::host_vector<float> Y_h; thrust::host_vector<float> Z_h; typedef thrust::tuple<float,float,float> Float3; typedef thrust::device_vector<float>::iterator FloatIterator; typedef thrust::tuple<FloatIterator, FloatIterator, FloatIterator> FloatIteratorTuple; typedef thrust::zip_iterator<FloatIteratorTuple> Float3Iterator; struct gridTransform { float k; gridTransform(float _k) { k=_k; } __host__ __device__ Float3 operator()(Float3 &p1) const { float lx1=roundf(thrust::get<0>(p1)/k); float ly1=roundf(thrust::get<1>(p1)/k); float lz1=roundf(thrust::get<2>(p1)/k); return Float3(lx1,ly1,lz1); } }; void Gpu_Functions::Decimation() { thrust::device_vector<float> X_d(X_h); thrust::device_vector<float> Y_d(Y_h); thrust::device_vector<float> Z_d(Z_h); // Storage for result of each transformations thrust::device_vector<Float3> result(N); // Now we'll create some zip_iterators for A and B Float3Iterator A_first = thrust::make_zip_iterator(make_tuple(X_d.begin(), Y_d.begin(), Z_d.begin())); Float3Iterator A_last = thrust::make_zip_iterator(make_tuple(X_d.begin(), Y_d.begin(), Z_d.begin())); // vertices transformation generate duplicate vertices thrust::transform(A_first, A_last, result.begin(), gridTransform(0.01)); // sort vertices to bring duplicates together thrust::sort(result.begin(), result.end()); // find unique vertices and erase redundancies result.erase(thrust::unique(result.begin(), result.end()), result.end()); }
gridTransform::operator() needs to take a const Float3 &. I guess Thrust doesn't implement a cast from their internal thrust::detail::tuple_of_iterator_references<float &, float &, float &> to the non-const tuple. The reason for this design decision is probably that for a non-const reference the behavior would be somewhat unexpected: Writing something to this tuple would probably not result in a change to the input vectors in device memory, but only to some temporary tuple in registers.
70,769,321
70,769,505
Can a variable and a method have the same name in C++?
class Controller { bool isBackendActive(); void anotherMethodDoingSomething(); } Can I declare a boolean variable with the same name as a method so that I can use it like this: void Controller::anotherMethodDoingSomething() { bool isBackendActive = isBackendActive(); if (aBoolean && isBackendActive) { ... LOG("bla" + isBackendActive) } else if (!isBackendActive) { ... } else ... } Thank you a lot for your input in advance.
Without discussing merits (or lack thereof), yes, you can disambiguate a member from a local variable rather easily. bool const isBackendActive = this->isBackendActive(); or bool const isBackendActive = Controller::isBackendActive(); Will work (and might as well be const correct).
70,769,513
70,769,576
Rotate through a zero based range for positive and negative numbers
Say I have a zero-based range like [0, 1, 2, 3, 4] these are essentially the indexes of an array with size = 5. Is it possible to use a signed integer variable to continuously loop up or down in that range? By up or down, I mean that the variable is permitted to perform arbitrarily many increment or decrement operations: ++index; --index; index += offset; index -= offset; So for example decrementing the index should map to following values: index = 2; while (/*...*/) { --index; index_in_range(index, 5); } The function index_in_range(index, 5) would output: 1, 0, 4, 3, 2, 1, 0, 4, 3, 2, 1, .... and so on The positive case is just a modulo operation over the range size, but for the negative I can't figure out how the mapping goes. EDIT : The requested function index_in_range(int idx, int range) takes an arbitrary integer, i.e. could be called as index_in_range(-245, 14). The example given does use a decrement operator but I never said I'm only offsetting by one each time.
C made a really poor decision for % to round towards zero, rather than be a straightforward floor, so the math's clunkier than it has to be. Basically, though, you want (index % size + size) % size. That code starts by chopping off the negative or positive multiples to bring the index into the range (-size, size), adds size to map it into (0,size*2), and a final % to map it into [0,size). If size is not known at compile time, it's likely more performant to replace everything after the first modulus with a conditional: index %= size; if(index < 0) index += size;.
70,769,545
70,770,090
Why in range for loop do begin/end need to be copyable?
When looking at what range-based for loops actually do here: https://en.cppreference.com/w/cpp/language/range-for#Explanation, I see that the begin_expr and end_expr are taken by value, i.e. using copy constructor: auto __begin = begin_expr ; auto __end = end_expr ; Is there a reason the begin/end are taken like that, or is it an oversight? Wouldn't it be better to either move them: auto __begin = std::move(begin_expr) ; auto __end = std::move(end_expr) ; or to take them by forwarding ref: auto && __begin = begin_expr ; auto && __end = end_expr ;
Is there a reason the begin/end are taken like that, or is it an oversight? Wouldn't it be better to either move them: In general no, because such specification could potentially prohibit copy elision. Why in range for loop do begin/end need to be copyable? The initialisation that you quote doesn't generally necessitate the iterators to be copyable, except in an unusual case where begin / end return an lvalue reference. I'm not sure if anyone cares about such case, given that would violate concept requirements.
70,770,596
70,770,758
C++ Arduino ESP8266 fucntion gives an exception, but running the same directly in loop works fine
I wrote function which should make a url request. function: int updateX(float x) { if(WiFi.status() == WL_CONNECTED) { WiFiClient client; HTTPClient http; String sendStr = "192.168.1.1/updateXdeg?xDegVal="+String(x); http.begin(client, sendStr); int httpCode = http.GET(); http.end(); } else { Serial.println("Wifi disconnected"); } } when I execute the function in the main loop I get exception 0 --------------- CUT HERE FOR EXCEPTION DECODER --------------- Exception (0): epc1=0x40201145 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000 >>>stack>>> ctx: cont sp: 3ffffc70 end: 3fffffc0 offset: 0190 3ffffe00: 3fffdad0 00000000 41b1999a 40201138 3ffffe10: 00000000 00000000 60831200 00000000 3ffffe20: 3f010000 00001388 00000000 40212205 3ffffe30: 00000000 00000000 00001a24 00000000 3ffffe40: 00000000 00000430 00000000 00000000 3ffffe50: 0011001f 00000000 00000000 4020fdb5 3ffffe60: 00000000 00000000 00000000 00000000 3ffffe70: ffffffff 000e0000 00000000 3ffe000a 3ffffe80: 00000000 00000020 00000000 00000000 3ffffe90: 00000000 40207dec 00000000 00001388 3ffffea0: 3fffdad0 00000000 00000000 00000000 3ffffeb0: 00000000 00000000 0024002f 00000000 3ffffec0: 00000000 0024002f 00000000 40201b60 3ffffed0: 3fffdad0 00000000 3ffee614 402011e7 3ffffee0: 3fffff64 00000000 000b000f 00000000 3ffffef0: ff010050 fe001388 00000000 0015001f 3fffff00: 00000000 00000000 00000000 00000000 3fffff10: 00000000 0000001f 00000000 00000000 3fffff20: 0011001f 00000000 00000000 40205db4 3fffff30: 00000000 00000000 00000000 00000000 3fffff40: ffffffff 18b2b801 00000000 3ffe000a 3fffff50: 00000000 3ffe8848 00000000 00000000 3fffff60: 00000000 40207dec 00000000 00001388 3fffff70: 000010e1 00000000 00000000 3ffef41c 3fffff80: 00000000 00000000 002a002f 00000000 3fffff90: 00000000 002a002f 00000000 402010a2 3fffffa0: feefeffe 00000000 3ffee614 40204bb8 3fffffb0: feefeffe feefeffe 3ffe85d8 40100b51 <<<stack<<< --------------- CUT HERE FOR EXCEPTION DECODER --------------- this is the decoded stack result: 0x40201138: updateX(float) at C:\Users\User\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2\cores\esp8266/WString.h line 79 0x40212205: tcp_enqueue_flags at core/tcp_out.c line 1085 0x4020fdb5: tcp_close_shutdown_fin at core/tcp.c line 448 0x40201b60: WiFiClient::~WiFiClient() at C:\Users\User\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2\libraries\ESP8266WiFi\src\WiFiClient.cpp line 101 0x40205db4: uart_write(uart_t*, char const*, size_t) at C:\Users\User\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2\cores\esp8266\uart.cpp line 546 0x402010a2: setup() at C:\Users\User\OneDrive - sluz\Dokumente\Arduino\sketch_jan19b/sketch_jan19b.ino line 28 0x40204bb8: loop_wrapper() at C:\Users\User\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\3.0.2\cores\esp8266\core_esp8266_main.cpp line 201 When I run the same code from the updateX function directly in the main loop it works perfectly fine.
My function was declared to return an integer, but I didn't return anything.
70,770,614
70,770,642
C++ camera component can't look up or down
I replaced the standard blue print camera with a c++ version so it works with my other functions that have been converted to c++ m_camera = CreateDefaultSubobject<UCameraComponent>(TEXT("camera")); but for some reason even though the m_camera node is connected to everything the blueprint node was I can’t look up or down. is there a way to fix this? I have done nothing to change the mouse input part of the default blueprint and the components that were part of the original camera were moved over to the c++ camera I also can't see the details panel for the camera
Check your values for UseControllerRotation To see details for the camera it has to have a metatag EditAnywhere in the .h UPROPERTY(EditAnywhere) UCameraComponent* m_Camera
70,770,677
70,770,729
why C++ recognizes an uninitialized raw-pointer as true?
Why the following code produces a seg-fault //somewhere in main ... int *pointer; if(pointer) cout << *pointer; ... But slightly changed following code doesn't //somewhere in main ... int *pointer = nullptr; if(pointer) cout << *pointer; ... the question is what in C++ makes an uninitialized pointer true - and leads to a crash
Why C++ Recognizes an uninitialized Raw Pointer (or say a daemon) as true? The behaviour may appear to be so, because the behaviour of the program is undefined. Why the following code produces a SEGMENTATION FAULT!!! Because the behaviour of the program is undefined, and that is one of the possible behaviours. But slightly changed following code doesn't Because you don't read an indeterminate value in the changed program, and the behaviour of that program is well defined, and the defined behaviour is that the if-statement won't be entered. In conclusion: Don't read uninitialised variables. Otherwise you'll end up with a broken, useless program. Although a compiler isn't required to diagnose undefined behaviour for you, luckily high quality compilers are able to detect such simple mistake. Here is example output: warning: 'pointer' is used uninitialized [-Wuninitialized] if(pointer) ^~ Compilers generally cannot detect all complex violations. However, runtime sanitisers can detect even complex cases. Example output: ==1==WARNING: MemorySanitizer: use-of-uninitialized-value Aside from reading uninitialised values, even if it was initialised, if (pointer) doesn't necessarily mean that you're allowed to indirect through the pointer. It only means that the pointer isn't null. Besides null, other pointer values can be unsafe to indirect through.
70,770,818
70,772,283
Need help to store the record of the current student in the students array
I have to develop a C++ program that reads the student’s name and scores from a file and store them in an array of Student struct objects, then calculate and display each student’s final grade based on the following criteria: midterm exam is counted for 25% of the final grade, final exam is counted for 25% of the final grade and average of 4 labs is counted for 50% of the final grade. But my knowledge is “limited” and more when it comes to using structures so there are things that I'm not sure how to do or implement things(look at the comments in the program below, basically with that I need help). I've tried a few methods but so far none have worked properly. And unfortunately, I can't change much of the "template" that they’ve provided me(They've provided me with the variables, or rather some of them, letterGrade, Student students[24], newStudent, etc..)... so that has made things a bit more complicated for me... I'm not one of those who usually ask for help. In fact, I would like to solve it myself, but I don't have much time... I'd appreciate some pointers or something, thank you. The format of the file is --- // student name // midterm exam scores, final exam scores // lab1 score, lab2 score, lab3 score, lab4 score e.g., Joe Doe 90.8 89.5 67 89.2 99.0 100.0 Susan F. Smith 95.5 94.0 78.5 90 87.5 57 Sam Grover 78 100.0 79.5 69.4 90.0 88.5 Here is what I've done so far: #include <iostream> #include <cstdlib> #include <string> #include <fstream> using namespace std; /* structure */ struct Student { string name; double midTerm; double finalExam; double lab1; double lab2; double lab3; double lab4; }; /* function prototype */ double calculateGrade(Student s); /* main function */ int main(void) { Student newStudent; Student students[24]; ifstream inFile; int numStudent = 0; char letterGrade = ' '; inFile.open("students.txt"); if (!inFile) cerr << "Unable to open file.\n"; // read the first student’s record, write some code here double pct; while (inFile) { // call calculateGrade function to calculate student’s final numeric score // and update student’s record, write some code here pct = calculateGrade(newStudent); // store the current student record in the students array and update numStudent // write some code here // ignore the ‘\n’ at the end of current student record in the data file // before reading next student record, write your code here // read next student record, write some code here numStudent++; } for (int i = 0; i < numStudent; i++) { if (pct >= 90.0) letterGrade = 'A'; else if (pct <= 89.9 && pct >= 80.0) letterGrade = 'B'; else if (pct <= 79.9 && pct >= 70.0) letterGrade = 'C'; else if (pct <= 69.9 && pct >= 60.0) letterGrade = 'D'; else letterGrade = 'F'; cout << students[i].name << "'s final grade is " << pct << "% (grade: " << letterGrade << ")" << endl; } exit(EXIT_SUCCESS); } double calculateGrade(Student s) { double exams, labs; exams = 0.25 * (s.midTerm) + 0.25 * (s.finalExam); labs = 0.125 * (s.lab1 + s.lab2 + s.lab3 + s.lab4); return (exams + labs); } An example of the output would be: David Smith’s final grade is 85.42% (grade: B) Ian Davis's final grade is 97.34% (grade: A) ...
You should use the C++ goodies, and learn to be more conservative with the idioms. main should be int main() or int main(int argc, char *argv[]). On some environments you can also use int main(int argc, char *argv[], char **environ) but never use the ugly void main(). Despite being equivalent in C++ int main(void) will only unsettle future readers. In C++ a class (or a struct because it is the same thing) can contain methods. Instead of building a free function using a single argument that is an instance of a class it is generally better to make a method from it. When you detect an error condition and write a fatal error message, you should not continue the program flow. The injectors (resp. extractors) can be used to directly extract (resp. write) an object from (rest. into) a stream. It generally gives a more idiomatic code. As you said that Student students[24] was provided I kept it, but in fact a single Student could be because you could print at read time. Here I have separated the reading of the records from the prints. SO here is a possible code: #include <iostream> #include <string> #include <fstream> // avoid using namespace std because it really import too many symbols using std::string; using std::ifstream; using std::istream; using std::cerr; using std::cout; using std::endl; /* structure */ struct Student { string name; double midTerm; double finalExam; double lab[4]; // making lab an array allows iterating on it // you can directly "cache" the computed values in the object itself double grade; string letterGrade; /* function prototype - better to make it a method */ void calculateGrade(); }; // an extractor for the Student class istream& operator >> (istream& in, Student& student) { if (!std::getline(in, student.name)) return in; // immediately give up on eof in >> student.midTerm >> student.finalExam; for (double& lab : student.lab) { in >> lab; } if (in) { student.calculateGrade(); // skip the end of last line because we want to use getline... if (in.ignore().eof()) { // but do not choke on end of file in.clear(); } } return in; } /* main function */ int main() { Student newStudent; Student students[24]; ifstream inFile; unsigned nStudents = 0; inFile.open("students.txt"); if (!inFile) { cerr << "Unable to open file.\n"; return EXIT_FAILURE; } // C++ allows to directly iterate any container including a plain array for (Student& student : students) { inFile >> student; // as we iterate through references we can change the object if (inFile) { nStudents++; } else { // give up on error or eof if (!inFile.eof()) { // but only write a message on error cerr << "Error reading file.\n"; } break; } } // time to display the results for (int i = 0; i < nStudents; i++) { cout << students[i].name << "'s final grade is " << students[i].grade << "% (grade: " << students[i].letterGrade << ")" << endl; } exit(EXIT_SUCCESS); } // the method implementation void Student::calculateGrade() { double exams, labs; exams = 0.25 * (midTerm) + 0.25 * (finalExam); labs = 0.125 * (lab[0] + lab[1] + lab[2] + lab[3]); grade = (exams + labs); if (grade >= 90.0) letterGrade = 'A'; else if (grade <= 89.9 && grade >= 80.0) letterGrade = 'B'; else if (grade <= 79.9 && grade >= 70.0) letterGrade = 'C'; else if (grade <= 69.9 && grade >= 60.0) letterGrade = 'D'; else letterGrade = 'F'; }
70,771,600
70,779,270
How do I compare single multibyte character constants cross-platform?
As I am writing a cross-platform application, I want my code to work on both platforms. In Windows, I use this code to compare 2 single characters. for( int i = 0; i < str.size(); i++ ) if( str.substr( i, 1 ) == std::string( "¶" ) ) printf( "Found!\n" ); Now, in Linux, the character is not found. It is found when I change the substring to a length of 2. for( int i = 0; i < str.size(); i++ ) if( str.substr( i, 2 ) == std::string( "¶" ) ) printf( "Found!\n" ); How do convert this character comparison code to be cross platform?
Solved using str.compare() and size() of character string: std::string str = "Some string ¶ some text ¶ to see"; std::string char_to_compare = "¶"; for( int i = 0; i < str.size(); i++ ) if( str.compare( i, char_to_compare.size(), char_to_compare ) == 0 ) printf( "Found!\n" );
70,772,159
70,775,635
Executing C functions from C++ file results in linker error: "conflicting declaration with 'C' linkage" and "previous declaration 'C++' linkage
I am attempting to execute a C function from within a C++ file in the Arduino framework. The function I am trying to run, GuiLib_ShowScreen, appears in GuiLib.h and GuiLib.c as follows (the files are massive so for convenience and relevance sake I included only definitions): extern void GuiLib_ShowScreen( const GuiConst_INT16U StructureNdx, GuiConst_INT16S CursorFieldToShow, GuiConst_INT8U ResetAutoRedraw) { ... } And the file from which I am trying to include GuiLib_ShowScreen: #ifndef _DISPLAY_DRIVER_H_ #define _DISPLAY_DRIVER_H_ #include <TFT_eSPI.h> #include <SPI.h> #include <ac.h> #include <stdio.h> #include "gui/GuiLib.h" #define USE_DMAA_TO_TFT extern "C" { void GuiLib_ShowScreen(const GuiConst_INT16U StructureNdx, GuiConst_INT16S CursorFieldToShow, GuiConst_INT8U ResetAutoRedraw); } class display_ { public: TFT_eSPI tft; bool getStatus(); void initPWM(); void writePWM(int duty); }; #endif And my main.cpp: #include "display_driver.h" void TaskPushDMA(void *pvParameters) { while (true) { GuiLib_ShowScreen(GuiStruct_main_0, GuiLib_NO_CURSOR, GuiLib_RESET_AUTO_REDRAW); vTaskDelay(1000); } } My issue is when compiling, I get a linker error that looks like this: In file included from src\main.cpp:6:0: src/display_driver.h:14:129: error: conflicting declaration of 'void GuiLib_ShowScreen(short unsigned int, short int, unsigned char)' with 'C' linkage void GuiLib_ShowScreen(const GuiConst_INT16U StructureNdx, GuiConst_INT16S CursorFieldToShow, GuiConst_INT8U ResetAutoRedraw); ^ In file included from src/display_driver.h:8:0, from src\main.cpp:6: src/gui/GuiLib.h:1847:13: note: previous declaration with 'C++' linkage extern void GuiLib_ShowScreen( ^ From what I am getting from this, is it seems to be suggesting that the original linkage is C++, which is strange considering the definition is in a C file. I've read here as well as previously opened issues here yet no luck. I also attempted creating a conditional like such: #ifdef __cplusplus extern "C" int foo(int, int); // C++ compiler sees this #else int foo(int, int); // C compiler sees this #endif
After trying suggestions from the comments, this cleared out the error. I included the library outside the scope after extern "C" and changed the parameters of GuiLib_ShowScreen() to their native types, defined in the library as #define GuiConst_INT16U unsigned short. There was a compatibility issue placing the include statement within the scope, and because my original error stated previous declaration with 'C++' linkage it seems apparent that the include statement was interpreted automatically as a C++ header instead of C. extern "C" { void GuiLib_ShowScreen(unsigned short StructureNdx, signed short CursorFieldToShow, unsigned char ResetAutoRedraw); } #include "gui/GuiLib.h"
70,772,186
70,772,722
Is there an easy way to copy an instance of a class in C++?
I'm trying to make a step based puzzle game (kind of like Baba Is You) and I need to store the state of the level at each step. So I'm using classes for the level, entities and some other things, and I was wondering if I can use default constructors like "Level(Level &&)" or "Level(const Level &)" I saw proposed by autocompletion to make a copy of the level as it is, but I can't grasp how they work from the documentation. The main idea was to have each level have its previous step (the copy of the level at the previous step) as an attribute, so that the game can work out any step recursively. The question is : is any of this possible? Because the only other way I see to do this is by making a method for my class that will simply create a new blank level and set all the attributes of this new level to those of the actual level, then return it and store it in the main scope. And this seems to be pretty bad because it requires to have evrything public or another method that sets every private attribute to a new value. If you want to give a look at the code it's here : https://github.com/Leroymilo/SwapCpp/tree/main/Experimental but it's not really clean since I'm starting in C++, and I believe from what I know that this is more of a technical question that doesn't involve correcting what I did (hopefully).
use default constructors like Level(Level &&) or Level(const Level &) Level(Level &&) is the move constructor. You don't want that, because you don't want to damage the original object Level(Level const &) is the copy constructor, which is for making a duplicate of an existing object without altering the original. This is exactly what you're asking for, and should be covered pretty early by any competent book in the section on writing classes. for reference, "default constructor" means specifically Level() - the constructor with no arguments. This is a well-known term that should also be described in any competent book. The compiler-generated versions of these constructors are sometimes described as defaulted (and can be requested like Level(Level const &) = default; in situations where they wouldn't be generated automatically, or just to make it explicit) - but it's important not to confuse them with the default constructor (which may itself be defaulted if you don't provide one). Whether the compiler-generated copy constructor will actually do the right thing for you depends entirely on the data members and semantics of your class, which you haven't shown. In general, it will work as a shallow copy so long as you don't use owning raw pointers or non-copyable types like std::unique_ptr. The std::shared_ptr is particularly suitable for automatic shallow copying where you want shared ownership. If you want a deep copy, you either need to write the copy constructor by hand or use (ie, find or write) a deep-copying smart pointer. Either way, see the Guidelines on Resource Management for recommendations that will help the compiler generate correct constructors and destructors for you.
70,772,241
70,772,600
Xml without indent char but with new line
Is there a way to write xml using boost::property_tree, without indent characters but with new line? Consider this code using namespace boost::property_tree; int main() { ptree tree; ptree* root = &tree.add("root", ""); root->add("something", "yes"); root->add("something2", "no"); write_xml("test.xml", tree, std::locale(), xml_writer_settings<ptree::key_type>('\n', 0)); } When indent_count is set to 0, we get this format <?xml version="1.0" encoding="utf-8"?> <root><something>yes</something><something2>no</something2></root> What I'm trying to achieve is this: <?xml version="1.0" encoding="utf-8"?> <root> <something>yes</something> <something2>no</something2> </root> Does anyone have an idea how to do this without adding '\n' through file manipulation? I'm using boost 1_66.
It seems like you cannot do this. Take a look at: https://github.com/boostorg/property_tree/blob/d30ff9404bd6af5cc8922a177865e566f4846b19/include/boost/property_tree/detail/xml_parser_write.hpp#L76 bool want_pretty = settings.indent_count > 0; and then, at 101 line: if (want_pretty) stream << Ch('\n'); So, if you want to have new line delimiters, ya have to have one or more indenting chars in the settings.
70,772,672
70,772,833
Order of memory locations
What is the order of memory locations allocated by new operator? For the context, if we are implementing a linked list, then does the new nodes created successively have increasing memory locations?
What is the order of memory locations allocated by new operator? The order is unspecified by the language. The order is what-ever the language implementation chooses it to be. if we are implementing a linked list, then does the new nodes created successively have increasing memory locations? If you use the default allocator, then they could have; but they might not have. And if they do have, that may be incidental. There are no guarantees either way. If you write an allocator of your own, then you are in control of the allocations.
70,772,818
70,773,460
how to prevent priority queue from having duplicate values at c++
now I'm trying to use priority queue in c++ like this struct compare { bool operator()(const int &a, const int &b) { return weight[a] < weight[b]; } }; priority_queue<int, vector<int>, compare> q; but I want it to ignore any duplicate values Is it possible using any technique to do this? or should I build my priority_queue DS
The answer is creating a custom container for the std::priority_queue: template <typename T> class Vector : public std::vector<T> { public: using std::vector<T>::vector; void push_back(const T &value) { if (std::find(this->begin(), this->end(), value) == this->end()) std::vector<T>::push_back(value); } }; int main() // { std::vector<int> data = {0, 4, 1, 2, 2, 1, 3, 4}; std::vector<float> weight = {.3, .1, .6, .2, .5}; auto comp = [&weight](int first, int second) { return weight[first] < weight[second]; }; std::priority_queue<int, Vector<int>, decltype(comp)> queue(comp); for (auto item : data) queue.push(item); while (!queue.empty()) { cout << queue.top() << ", "; queue.pop(); } cout << endl; } Here I have inherited from std::vector and changed the push_back method to detect duplicates. But this is the efficient way of doing it (has complexity O(n)). We can create a custom queue with the same top, pop, empty, size, push functions as std::priority_queue: template <typename T, typename C> class Queue { std::set<T, C> impl; public: Queue(C compare) : impl(compare) {} const T &top() const { return *impl.begin(); } void pop() { impl.erase(impl.begin()); } bool empty() const { return impl.empty(); } std::size_t size() const { return impl.size(); } void push(const T &value) { impl.insert(value); } }; int main() // { std::vector<int> data = {0, 4, 1, 2, 2, 1, 3, 4}; std::vector<float> weight = {.3, .1, .6, .2, .5}; auto comp = [&weight](int first, int second) { return weight[first] > weight[second]; }; Queue<int, decltype(comp)> queue(comp); for (auto item : data) queue.push(item); while (!queue.empty()) { cout << queue.top() << ", "; queue.pop(); } cout << endl; } This method uses std::set to keep the order and has faster duplicate detection (has complexity O(log(n))).
70,773,087
70,773,293
C++ operator overloading [] and return types
I'm just revisiting C++, and I have a question about overloading of the [] operator, and more specifically why my program doesn't work. Given the following code in vec.cpp: double Vec::operator[](unsigned int i) const { return this->values[i]; } double & Vec::operator[](unsigned int i) { return this->values[i]; } These are defined in vec.h as methods to the Vec class, and if I do not use the operator in my main.cpp, all is fine and dandy. It compiles just as normal with no errors. However once I do this in my main function (which is using std::cout and std::endl): cout << a[0] << endl; Things go wrong. The errors I get are a bunch of candidate function template not viable: no known conversion from 'Vec' to 'char' for 2nd argument operator<<(basic_ostream<_CharT, _Traits>& __os, char __cn) where you can replace 'char' with any primitive data type. Here is a working example // In vec.h #pragma once #include <string> #include <iostream> class Vec { private: int dims; double *values; public: Vec(int dims, double values[]); double operator [](unsigned int i) const; double& operator[](unsigned int i); }; // In vec.cpp #include <iostream> #include <string> #include <cmath> #include "vec.h" using std::cerr, std::endl, std::cout; Vec::Vec(int dims, double values[]) { this->dims = dims; this->values = new double[dims]; for(int i = 0; i < dims; i++) { this->values[i] = values[i]; } } double Vec::operator[](unsigned int i) const { if(i >= this->dims) { cerr << "Elem out of range" << endl; } return this->values[i]; } double & Vec::operator[](unsigned int i) { if(i >= this->dims) { cerr << "Elem out of range" << endl; } return this->values[i]; } // In main.cpp #include <iostream> #include <string> #include "vec.h" using std::cout, std::endl; int main() { double avals[2]; avals[0] = 1.0; avals[1] = 2.0; Vec *a = new Vec(2, avals); cout << a[0] << endl; // Error occurs here return 0; } Can anyone help me sort this out?
In this declaration Vec *a = new Vec(2, avals); there is declared a pointer of the type Vec *. So an expression with the dereferenced pointer has the type Vec. So in this statement cout << a[0] << endl; the expression a[0] has the type Vec. It seems you mean ( *a )[0] or a[0][0]
70,773,117
70,773,336
A letter in a byte? C#
I have an imported C++ method that receives a byte parameter, but according to the documentation, I can send a letter to that parameter, this is the C++ and C# method: int WINAPI Sys_InitType(HID_DEVICE device, BYTE type) public static extern int Sys_InitType(IntPtr device, byte type); This causes me a syntax error in C#, how do I send a letter in that parameter? My code (A bit random): //CRASHES byte random = Convert.ToByte("A"); _ = RFIDReader.Sys_SetAntenna(g_hDevice, 0); int lol = RFIDReader.Sys_InitType(g_hDevice, random); _ = RFIDReader.Sys_SetAntenna(g_hDevice, 1); CError.Text = lol.ToString();
Convert.ToByte(string); doesn't do what you think it does, according to the documentation Converts the specified string representation of a number to an equivalent 8-bit unsigned integer. This would work byte random = Conver.ToByte("52"); which will return the byte 52. See here: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tobyte?view=net-6.0#system-convert-tobyte(system-string) As was pointed out in the comment already, you will have to use character instead of string, so either this byte random = Convert.ToByte('A'); or a simple cast to byte byte random = (byte)'A' In case it is unknown to you, which I didn't assume, a byte can only contain values of the range 0 - 255, while a character can contain everything within the specs of UTF-16. So this will not work byte random = Convert.ToByte('\u4542'); And result in the error: Value was either too large or too small for an unsigned byte. https://dotnetfiddle.net/anjxt5
70,773,154
70,773,428
Why can I use scalar type as the return type of operator->?
From cppreference: The overload of operator -> must either return a raw pointer, or return an object (by reference or by value) for which operator -> is in turn overloaded. However, I tested the following example, and it is accepted by GCC, Clang and MSVC: struct A { int operator->(); }; According to cppreference, the return type int is neither a pointer nor a type that overloads operator->. Why is this example correct? Where is this situation described in the standard? What is the intent of the standard to allow this?
While the standard doesn't directly place restrictions on the return type of operator->, it does describe what happens when the overloaded -> operator is used: 12.6.5 Class member access [over.ref] A class member access operator function is a function named operator-> that is a non-static member function taking no parameters. For an expression of the form     postfix-expression -> template(opt) id-expression the operator function is selected by overload resolution (12.4.1.2), and the expression is interpreted as      ( postfix-expression . operator -> () ) -> template(opt) id-expression. So when using your class, you can call the overloaded operator like a normal function by writing a.operator->(). But if you attempt to use the operator with a->name, this is interpreted as (a.operator->())->name which won't compile because it attempts to use -> on an int.
70,773,702
70,773,810
How to limit the template parameter to only floating point type
Is there a way to limit a template parameter T to a specific type or category? The below code works but I want to make it simpler: #include <iostream> #include <type_traits> template <typename T> constexpr auto func( const T num ) -> T { static_assert( std::is_floating_point_v<T>, "Floating point required." ); return num * 123; } int main( ) { std::cout << func( 4345.9 ) << ' ' // should be ok << func( 3 ) << ' ' // should not compile << func( 55.0f ) << '\n'; // should be ok } I want to get rid of the static_assert and write something like this: template < std::is_floating_point_v<T> > constexpr auto func( const T num ) -> T { return num * 123; } Any suggestions? Anything from type_traits or maybe concepts would be better.
The below code works but I want to make it simpler: You may combine abbreviated function templates and the std::floating_point concept for a condensed constrained function template definition: constexpr auto func(std::floating_point auto num) { return num * 123; } Note that this does not include an explicitly specified trailing return type T as in your original approach, but that for the current definition the deduced return type will be decltype(num), which is either float or double (or impl-defined long double). As @Barry points out in the comments below, if you require a trailing return type, say for an overload with a ref- and cv-qualified function parameter, then the brevity gain of abbreviated templates is lost to the added cost of complex trailing return type. // Contrived example: but if this was the design intent, // then no: skip the abbreviated function template approach. constexpr auto func(const std::floating_point auto& num) -> std::remove_cvref_t<decltype(num)> { /* ... */ } // ... and prefer template<std::floating_point T> constexpr auto func(const T& num) -> T { /* ... */ } // ... or (preferential) template<std::floating_point T> constexpr T func(const T& num) { /* ... */ }
70,774,255
70,774,469
How can I use Unique_ptrs with an class object having std::function as argument in the constructor
Problem Description We have 2 classes A and B. B has the following constructor: B(std::function<std::unique_ptr<A>()> a) I am trying to create a unique_ptr as in std::unique_ptr<B> aPtr = std::unique_ptr<B>(new B(std::function<std::unique_ptr<A>())); I can't figure out how to do it. It's not compiling and I can't really explain the error. How Can I create unique_ptr for class B? // Online C++ compiler to run C++ program online #include <iostream> #include <memory> #include <functional> class A { public: A(){} }; class B { public: B(std::function<std::unique_ptr<A>()> a):_a(std::move(a)) {} private: std::function<std::unique_ptr<A>()> _a; }; int main() { //std::unique_ptr<B> bPtr = std::unique_ptr<B>(new B(std::function<std::unique_ptr<A>())); return 0; }
auto bPtr = std::unique_ptr<B>(new B( std::function< std::unique_ptr<A>() > () )); // need to close the template ^ // need to construct an instance of ^^ You get the same a bit simpler by using std::make_unique: auto bPtr = std::make_unique<B>( std::function< std::unique_ptr<A>() >() ); // still as above ^^^ Edit: Adjustment to new question version: You have not yet provided a copy constructor – so you need to store the lambda instead of creating a B instance: auto l = []() { return std::make_unique<A>(); }; auto bPtr = std::unique_ptr<B>(new B(l)); // or: auto ptr = std::make_unique<B>(l); Note that this new edited version provides a factory function to the std::function object (the lambda!), while the initial variants constructed an empty one without function stored inside, so not callable!
70,774,419
70,774,606
OpenGL depth testing and blending not working simultaniously
I'm currently writing a gravity-simulation and I have a small problem displaying the particles with OpenGL. To get "round" particles, I create a small float-array like this: for (int n = 0; n < 16; n++) for (int m = 0; m < 16; m++) { AlphaData[n * 16 + m] = ((n - 8) * (n - 8) + (m - 8) * (m - 8) < 64); } I then put this in a GL_TEXTURE_2D with format GL_RED. In the fragment shader (via glDrawArraysInstanced), I draw the particles like this: color = vec4(ParticleColor.rgb, texture(Sampler, UV).r); This works as it should, producing a picture like this (particles enlarged for demonstration): As you can see, no artifacts. Every particle here is the same size, so every smaller one you see on a "larger" particle is in the background and should not be visible. When I turn on depth-testing with glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); I get something like this: So for the most part, this looks correct ("smaller" particles being behind the "bigger" ones). But I now have artifacts from the underlying quads. Weirdly not ALL particles have this behavior. Can anybody tell me, what I'm doing wrong? Or do depth-testing and blending not work nicely together? I'm not sure, what other code you might need for a diagnosis (everything else seems to work correctly), so just tell me, if you need additional code. I'm using a perspective projection here (of course for particles in 3D-space).
You're in a special case where your fragments are either fully opaque or fully transparent, so it's possible to get depth-testing and blending to work at the same time. The actual problem is, that for depth testing even a fully transparent fragment will store it's depth value. You can prevent the writing by explicitly discarding the fragment in the shader. Something like: color = vec4(ParticleColor.rgb, texture(Sampler, UV).r); if (color.a == 0.0) discard; Note, that conditional branching might introduce some additional overhead, but I wouldn't expect too many problems in your case. For the general case with semi-transparent fragments, blending and depth-testing at the same time will not work. In order for blending to produce the correct result, you have to depth sort your geometry prior to rendering and render from back to front.
70,774,468
70,775,393
Using a union to prevent destruction?
Related: How does =delete on destructor prevent stack allocation? First, I realize this sort of thing is playing with fire, tempting UB. I'm asking to get a better understanding of corner-cases of unions. As I understand it, if I have a class with a c'tor and d'tor and put it in a union, the compiler will force me to tell it what to do about construction and destruction. As in #include <iostream> struct S { int x; S() : x(-1) { std::cout << "S()" << std::endl; } ~S() { std::cout << "~S()" << std::endl; } static S& instance() { union DoNotDestruct { S value; DoNotDestruct() : value() {} ~DoNotDestruct() {} }; static DoNotDestruct inst; return inst.value; } }; int main() { return S::instance().x; } which just reports construction, not destruction. However, it appears that if I have a deleted destructor, that doesn't work; I have to use placement-new: #include <new> // Placement-new version: struct S0 { S0() {} ~S0() = delete; static S0& instance() { union DoNotDestruct { S0 value; DoNotDestruct() { // I believe value isn't constructed yet. new (&value) S0; // Placement-new. } ~DoNotDestruct() {} // Omit S0's d'tor. }; static DoNotDestruct inst; return inst.value; } }; // Init version: struct S1 { S1() {} ~S1() = delete; static S1& instance() { union DoNotDestruct { S1 value; DoNotDestruct() : value{} {} // Why does this line want S1::~S1() to exist? ~DoNotDestruct() {} // Omit S1's d'tor. }; static DoNotDestruct inst; return inst.value; } }; https://godbolt.org/z/7r4ebszor Here, S0 is happy, but S1 complains on the constructor line that S1::~S1() is deleted. Why? I tried adding noexcept on the thought that in a class, if you have multiple members, the 0th member needs to be destructible if any subsequent c'tors throw. It looks like even a class with a deleted d'tor can't itself hold an indestructible member even if the c'tors are all noexcept. It gives the same error as the union: https://godbolt.org/z/jx3W1YEPf
[class.dtor]/15 says that a program is ill-formed if a potentially invoked destructor is defined as deleted. [class.base.init]/12 says that a destructor of a potentially constructed subobject of a class is potentially invoked in a non-delegating constructor. [special]/7 says that all non-static data members are potentially constructed subobjects, although the sentence is qualified a bit weirdly I think ("For a class, [...]"). I don't see any exceptions in this for single-member classes, unions or noexcept. So it seems to me that GCC is correct for S1. Clang is also the only compiler out of Clang, GCC, ICC and MSVC that doesn't reject this version. For S0 however, this reasoning would also apply, making it ill-formed as well. However none of the four compilers agrees on that, so maybe I am wrong. The quoted wording comes mostly from CWG issue 1424. Clang lists its implementation status currently as unknown (https://clang.llvm.org/cxx_dr_status.html), as does GCC (https://gcc.gnu.org/projects/cxx-dr-status.html).
70,774,914
70,791,799
ld: can't open output file for writing: execs/aligns, errno=2 for architecture arm64
I created a small program to learn some concepts of STL, but when I compile, I get following error: ld: can't open output file for writing: execs/aligns, errno=2 for architecture arm64 clang: error: linker command failed with exit code 1 (use -v to see invocation) Compiled with: g++ --std=c++17 aligns.cpp -o execs/aligns I am using M1 MacBook. Thanks in advance!!!
I have finally found the solution! Folder 'execs' simply didn't exist)))
70,775,025
70,775,136
c++ Two Classes Refering To Each Other
i'm working with c++. I need to create two classes that refering to each other. Something like this: class A { private: B b; //etc... }; class B { private: A a; //etc... }; How can i do that? Sorry for my bad English and thanks you for helping me :)
You can't do that even in principle, because a single A object would contain a B which contains another A, which contains another B and another A ... If you just want a reference, you can simply do class B; // forward declaration class A { B& b_; // reference public: explicit A(B& b) : b_(b) {} }; class B { A a_; public: B() : a_(*this) {} }; Now each B contains an A which refers to the B in which it sits. Do note however that you can't really do anything with b (or b_) inside A's constructor, because the object it refers to hasn't finished creating itself yet. A pointer would also work - and of course A and B can both have references instead of B containing an immediate object.
70,775,205
70,776,161
Implementing template specialized functions
I'm trying to allow a class to implement an interface, where the interface is templated to either allow an update internally or not. The code looks like this and works if the implementation is within the class declaration. If it is moved out (as shown here), I get a compiler error on Visual Studio 2019, and I can't understand why. All help is appreciated! The following code will not compile. If the out of class implementation and headers are modified to just use the code I commented out, it compiles and works as expected. #include <atomic> #include <cstdint> #include <memory> #include <iostream> #include <string> enum class EntryType { Read, ReadUpdate }; template <EntryType Type> class IXQ { public: virtual float GetValue() = 0; }; class X : public IXQ<EntryType::Read>, public IXQ<EntryType::ReadUpdate> { public: float IXQ<EntryType::Read>::GetValue(); /* float IXQ<EntryType::Read>::GetValue() { return _x; } */ float IXQ<EntryType::ReadUpdate>::GetValue(); /* float IXQ<EntryType::ReadUpdate>::GetValue() { _counter++; return _x; } */ float _x = 10.0F; std::atomic<std::int32_t> _counter = 0; }; float X::IXQ<EntryType::Read>::GetValue() { return _x; } float X::IXQ<EntryType::ReadUpdate>::GetValue() { _counter++; return _x; }; int main(int argc, char* argv[]) { { auto k = std::make_unique<X>(); auto ptrQ = static_cast<IXQ<EntryType::Read>*>(k.get()); std::cout << std::to_string(ptrQ->GetValue()) << std::endl; std::cout << k->_counter.load() << std::endl; } { auto k = std::make_unique<X>(); auto ptrQ = static_cast<IXQ<EntryType::ReadUpdate>*>(k.get()); std::cout << std::to_string(ptrQ->GetValue()) << std::endl; std::cout << k->_counter.load() << std::endl; } return 0; }
1. Microsoft-specific syntax The syntax you're using to override GetValue() is not standard c++. class X : public IXQ<EntryType::Read> { public: float IXQ<EntryType::Read>::GetValue() { /* ... */ } } This is a Microsoft-Specific Extension for C++ called Explicit Overrides (C++) and is intended to be used with __interfaces (also a microsoft-specific extension to c++). __interfaces do not officially support c++ templates due to them being intended mostly for COM Interfaces, e.g.: [ object, uuid("00000000-0000-0000-0000-000000000001"), library_block ] __interface ISomething { // properties [ id(0) ] int iInt; [ id(5) ] BSTR bStr; // functions void DoSomething(); }; It's suprising that float IXQ<EntryType::Read>::GetValue() { /* ... */ } works at all. 2. Standard C++-compliant solutions In standard C++ the overriden function is determined by the name & arguments alone, so your only option is to override both of them. e.g.: class X : public IXQ<EntryType::Read>, public IXQ<EntryType::ReadUpdate> { public: // will be the implementation for both IXQ<EntryType::Read> & IXQ<EntryType::ReadUpdate> float GetValue() override; }; float X::GetValue() { /* ... */ } Another standard-compliant way would be to create 2 classes that inherit from the given interfaces & then let X inherit from both of them: class XRead : public IXQ<EntryType::Read> { public: float GetValue() override { /* ... */ } }; class XReadUpdate : public IXQ<EntryType::ReadUpdate> { public: float GetValue() override { /* ... */ } }; class X : public XRead, public XReadUpdate { /* ... */ }; If you want to share state between XRead & XReadUpdate, you'd have to introduce another level, e.g.: class XBase { public: virtual ~XBase() = default; protected: float value; }; class XRead : public virtual XBase, public IXQ<EntryType::Read> { float GetValue() override { return value; } }; class XReadUpdate : public virtual XBase, public IXQ<EntryType::ReadUpdate> { float GetValue() override { return value; } }; class X : public XRead, public XReadUpdate { /* ... */ }; 3. Possible recommendations for API Design Keep in mind though that this type of API design will be rather complicated to use, because you always need to cast to the specific interface first before you can call the function because X{}.GetValue() would be ambigous. e.g.: X x; IXQ<EntryType::Read>& read = x; std::cout << read.GetValue() << std::endl; IXQ<EntryType::ReadUpdate>& update = x; std::cout << update.GetValue() << std::endl; // this is *not* possible, GetValue() is ambigous // std::cout << x.GetValue() << std::endl; I'd recommend separating both interfaces & using different method names, e.g.: godbolt example struct IXQReadonly { virtual ~IXQReadonly() = default; virtual float GetValue() = 0; }; struct IXQ : IXQReadonly { virtual float GetValueUpdate() = 0; }; class X : public IXQ { public: X() : value(0.0f), counter(0) { } float GetValue() override { return value; } float GetValueUpdate() override { ++counter; return value; } private: float value; std::atomic<int> counter; }; This comes with a whole set of benefits: You can call GetValue() / GetValueUpdate() directly on X, no need to convert to an interface first X x; x.GetValue(); x.GetValueUpdate(); It is immediately clear from the method name if it will update the counter or not A function that is given an IXQ can call a function that expects IXQReadonly, but not the other way round: (so you can "downgrade" a read-write interface to readonly, but not "upgrade" a readonly interface to read-write) void bar(IXQReadonly& r) { r.GetValue(); /* we can't do GetValueUpdate() here */ } void foo(IXQ& x) { bar(x); x.GetValueUpdate(); } Additionally remember to declare the destructor as virtual (at least in the top-most class / interface), otherwise funny things tend to happen if you try to delete an instance of X through a pointer to one of its bases / interfaces.
70,775,446
70,778,214
Can OpenMP's SIMD directive vectorize indexing operations?
Say I have an MxN matrix (SIG) and a list of Nx1 fractional indices (idxt). Each fractional index in idxt uniquely corresponds to the same position column in SIG. I would like to index to the appropriate value in SIG using the indices stored in idxt, take that value and save it in another Nx1 vector. Since the indices in idxt are fractional, I need to interpolate in SIG. Here is an implementation that uses linear interpolation: void calcPoint(const Eigen::Ref<const Eigen::VectorXd>& idxt, const Eigen::Ref<const Eigen::Matrix<short int, -1, -1>>& SIG, double& bfVal) { Eigen::VectorXd bfPTVec(idxt.size()); #pragma omp simd for (int j = 0; j < idxt.size(); j++) { int vIDX = static_cast<int>(idxt(j)); double interp1 = vIDX + 1 - idxt(j); double interp2 = idxt(j) - vIDX; bfPTVec(j) = (SIG(vIDX,j)*interp1 + SIG(vIDX+1,j)*interp2); } bfVal = ((idxt.array() > 0.0).select(bfPTVec,0.0)).sum(); } I suspect there is a better way to implement the body of the loop here that would help the compiler better exploit SIMD operations. For example, as I understand it, forcing the compiler to cast between types, both explicitly as the first line does and implicitly as some of the mathematical operations do is not a vectorizable operation. Additionally, by making the access to SIG dependent on values in idxt which are calculated at runtime I'm not clear if the type of memory read-write I'm performing here is vectorizable, or how it could be vectorized. Looking at the big picture description of my problem where each idxt corresponds to the same "position" column as SIG, I get a sense that it should be a vectorizable operation, but I'm not sure how to translate that into good code. Clarification Thanks to the comments, I realized I hadn't specified that certain values that I don't want contributing to the final summation in idxt are set to zero when idxt is initialized outside of this method. Hence the last line in the example given above.
Probably no, but I would expect manually vectorized version to be faster. Below is an example of that inner loop, untested. It doesn’t use AVX only SSE up to 4.1, and should be compatible with these Eigen matrices you have there. The pIndex input pointer should point to the j-th element of your idxt vector, and pSignsColumn should point to the start of the j-th column of the SIG matrix. It assumes your SIG matrix is column major. It’s normally the default memory layout in Eigen but possible to override with template arguments, and probably with macros as well. inline double computePoint( const double* pIndex, const int16_t* pSignsColumn ) { // Load the index value into both lanes of the vector __m128d idx = _mm_loaddup_pd( pIndex ); // Convert into int32 with truncation; this assumes the number there ain't negative. const int iFloor = _mm_cvttsd_si32( idx ); // Compute fractional part idx = _mm_sub_pd( idx, _mm_floor_pd( idx ) ); // Compute interpolation coefficients, they are [ 1.0 - idx, idx ] idx = _mm_addsub_pd( _mm_set_sd( 1.0 ), idx ); // Load two int16_t values from sequential addresses const __m128i signsInt = _mm_loadu_si32( pSignsColumn + iFloor ); // Upcast them to int32, then to fp64 const __m128d signs = _mm_cvtepi32_pd( _mm_cvtepi16_epi32( signsInt ) ); // Compute the result __m128d res = _mm_mul_pd( idx, signs ); res = _mm_add_sd( res, _mm_unpackhi_pd( res, res ) ); // The above 2 lines (3 instructions) can be replaced with the following one: // const __m128d res = _mm_dp_pd( idx, signs, 0b110001 ); // It may or may not be better, the dppd instruction is not particularly fast. return _mm_cvtsd_f64( res ); }
70,776,453
70,776,798
What is the difference between __declspec( dllimport ) extern "C" AND extern "C" __declspec( dllimport )
Would there be any difference between both notations when compiling in a .c file or within a .cpp file ?
extern "C" and __declspec(dllimport) are totally orthogonal. extern "C" means that C linkage should be used for that symbol. I.e. no C++ name mangling will be applied. It also limits functions' interfaces to C-compatible things: built-in types, trivial structs, and pointers. Essentially, it tells the compiler and linker that a symbol should be found in the "C way" rather than the "C++ way". extern "C" is generally used for either calling C functions from C++ code or creating a C-compatible interface to C++ code. __declspec(dllimport) tells the linker that a symbol will be loaded dynamically at runtime from a DLL. The two can be combined as well. A function marked extern "C" __declspec(dllimport) will be dynamically linked and use C-style linkage.
70,776,943
70,777,056
gcc.exe vs cpp.exe vs g++.exe
I am using Visual Studio Code for the coding and for C/C++ I uses MinGW. When I click on configure default build task then I can see various options like C/C++:cpp.exe build active file(compiler: C:/MinGW/bin/cpp.exe),C/C++:g++.exe build active file (compiler: C:/MinGW/bin/g++.exe),C/C++:gcc.exe build active file(compiler: C:/MinGW/bin/gcc.exe),C/C++:g++.exe Task generated by Debugger (compiler: C:/MinGW/bin/g++.exe) C/C++:gcc.exe Task generated by Debugger (compiler: C:/MinGW/bin/g++.exe) and two more of g++ & GCC build active file....may anyone explain the need, role & difference among all these. also why there isn't a option of "Task generated by Debugger" for cpp.exe. thank you in advance.
cpp - The C and C++ preprocessor that replaces macros etc. Since you don't have a "Task generated by debugger" for this, it'll most likely be used in the same way for both debug and release builds. gcc - The C compiler that is used to compile C programs. g++ - The C++ compiler that is used to compile C++ programs
70,777,047
70,777,397
Difference in a C++ pointer behavior when incremented in the for loop definition vs inside for loop
I'm onto a leetcode problem (Floyd’s Cycle Detection Algorithm for Linked List) wherein I noticed a strange behavior on the pointer states. When I change the pointer state inside the for loop, the program executes correctly (pointer states move to the right states): ListNode *detectCycle(ListNode *head) { if(!head or !head->next) return nullptr; ListNode *slow, *fast; for(slow = head, fast = head; fast && fast->next;) { slow = slow->next, fast = fast->next->next; // This hops the pointers correctly if(slow == fast) { slow = head; while(slow != fast) { slow = slow->next; fast = fast->next; } return slow; } } return nullptr; } But when I state change slow & fast in the for loop definition, the state change is wrong and the program doesnt give the right output. ListNode *detectCycle(ListNode *head) { if(!head or !head->next) return nullptr; ListNode* slow, *fast; for(slow = head, fast = head; fast && fast->next; slow = slow->next, fast=fast->next->next) // Pointers dont hop correctly { if(slow == fast) { slow = head; while(slow != fast) { slow = slow->next; fast = fast->next; } return slow; } } return nullptr; } I dont know whats causing this. In my head, incrementing the pointers in the for loop definition vs immediately in the for loop should be the same thing. Can someone throw an insight as to why incrementing pointers within the loop vs in the for loop signature leads to different behavior?
A for (init-statement; condition; iteration-expression) { dostuff(); } maps to { init-statement while ( condition ) { dostuff(); iteration-expression ; } } so we get { slow = head, fast = head; while (fast && fast->next) { slow = slow->next, fast = fast->next->next; dostuff(); // for example purposes only. Not really replacible with a function } } and { slow = head, fast = head; while (fast && fast->next) { dostuff(); slow = slow->next, fast=fast->next->next; } } In the first, slow and fast are always updated before dostuff(). In the second, dostuff happens before slow and fast are updated, so the values of slow and fast used in dostuff will be different on the first loop iteration.
70,777,258
70,805,849
Constructing native object from NodeJS Addon
Expectation I want to to implement using a native NodeJS module that works like the javascript module below class C1{ make(){return new C2()} } class C2{} module.exports({C1, C2}) Approach My attempt was, (among some other failed attempts) // so.cpp #include <napi.h> class C1: public Napi::ObjectWrap<C1> { public: C1(const Napi::CallbackInfo &info); static void Initialize(Napi::Env& env, Napi::Object& target); Napi::Value make(const Napi::CallbackInfo &info); }; class C2: public Napi::ObjectWrap<C2> { static Napi::Function constructor; public: C2(const Napi::CallbackInfo &info); static void Initialize(Napi::Env& env, Napi::Object& target); static C2 *New(const std::initializer_list<napi_value>& args); }; Napi::Function C2::constructor; void C2::Initialize(Napi::Env& env, Napi::Object& target){ constructor = Napi::ObjectWrap<C2>::DefineClass(env, "C2", {}); target.Set("C2", constructor); } void C1::Initialize(Napi::Env& env, Napi::Object& target) { Napi::Function constructor = Napi::ObjectWrap<C1>::DefineClass(env, "C1", { Napi::ObjectWrap<C1>::InstanceMethod("make", &C1::make), }); target.Set("C1", constructor); } C2 *C2::New(const std::initializer_list<napi_value>& args){ return Napi::ObjectWrap<C2>::Unwrap(constructor.New(args)); } C2::C2(const Napi::CallbackInfo &info): Napi::ObjectWrap<C2>(info) {} C1::C1(const Napi::CallbackInfo &info): Napi::ObjectWrap<C1>(info) {} // make() {return new C2()} Napi::Value C1::make(const Napi::CallbackInfo &info){ C2 *jsclat = C2::New({}); return jsclat->Value(); } // module.exports = {C1, C2} Napi::Object Init(Napi::Env env, Napi::Object exports) { C1::Initialize(env, exports); C2::Initialize(env, exports); return exports; } NODE_API_MODULE(so, Init); Problem When I try to use the compiled module from javascript Node is terminated const m = require('bindings')('hello') const c1 = new m.c1() c1.make() // FATAL ERROR: Error::New napi_get_last_error_info // Aborted Environment If you want the same environment as I used, here you have a dockerfile. FROM node:13.8.0-alpine3.11 RUN apk add --upgrade git python3 g++ make WORKDIR /opt RUN git clone https://github.com/nodejs/node-addon-examples.git WORKDIR /opt/node-addon-examples/1_hello_world/node-addon-api/ RUN npm install \ && npm install --save-dev gyp && npx node-gyp configure COPY so.cpp hello.cc RUN npx node-gyp rebuild
You are not allowed to use constructor outside the function that created it - it is an automatic v8::Local reference that is allocated on the stack - you need a persistent reference to do this: #include <napi.h> class C1: public Napi::ObjectWrap<C1> { public: C1(const Napi::CallbackInfo &info); static void Initialize(Napi::Env &env, Napi::Object &target); Napi::Value make(const Napi::CallbackInfo &info); }; class C2: public Napi::ObjectWrap<C2> { static Napi::Function constructor; public: static Napi::FunctionReference *New; C2(const Napi::CallbackInfo &info); static void Initialize(Napi::Env& env, Napi::Object& target); }; Napi::FunctionReference *C2::New; void C2::Initialize(Napi::Env& env, Napi::Object& target){ Napi::Function constructor = Napi::ObjectWrap<C2>::DefineClass(env, "C2", {}); target.Set("C2", constructor); New = new Napi::FunctionReference(); *New = Napi::Persistent(constructor); } void C1::Initialize(Napi::Env& env, Napi::Object& target) { Napi::Function constructor = Napi::ObjectWrap<C1>::DefineClass(env, "C1", { Napi::ObjectWrap<C1>::InstanceMethod("make", &C1::make), }); target.Set("C1", constructor); } C2::C2(const Napi::CallbackInfo &info): Napi::ObjectWrap<C2>(info) {} C1::C1(const Napi::CallbackInfo &info): Napi::ObjectWrap<C1>(info) {} // make() {return new C2()} Napi::Value C1::make(const Napi::CallbackInfo &info){ Napi::Value c2 = C2::New->New({}); return c2; } // module.exports = {C1, C2} Napi::Object Init(Napi::Env env, Napi::Object exports) { C1::Initialize(env, exports); C2::Initialize(env, exports); return exports; } NODE_API_MODULE(so, Init);
70,777,344
70,777,836
How to write an infinite sequence compatible with std::ranges?
I would like to write a struct which will generate an infinite sequence of fibonacci numbers in a way compatible with std::ranges and range adaptors. So if I wanted the first 5 even fibonacci numbers, I would write something like this: #include <iostream> #include <ranges> using namespace std; int main() { auto is_even = [](auto a) { return a % 2 == 0; }; for (auto v : something | ranges::views::filter(is_even) | ranges::views::take(5)) std::cout << v << std::endl; return 0; } What "something" needs to be ? It seems to me that it has to be a class with a forward iterator, but I can't find any example.
Edit: As it was pointed out by 康桓瑋 in the comments, there has been a better, cleaner solution presented at Cppcon, link, by Tristan Brindle. I think this could serve as a quick reference to make custom iterator-based generators. By your requirements, something must be a std::ranges::view, meaning it must be a moveable std::ranges::range deriving from std::ranges::view_interface<something>. We can tackle all three with the following: #include <ranges> template<typename T> class fib : public std::ranges::view_interface<fib<T>>{ public: struct iterator; auto begin() const { return iterator{}; } auto end() const { return std::unreachable_sentinel; } }; Notice std::unreachable_sentinel which makes creating sequences without end really simple. We still have to define the iterator which does the actual work. In your case we want fib to be "the source" of the values, so our iterator should actually be std::input_iterator. There's some boiler plate code needed for that but it's basically just a type which can be incremented and dereferenced to yield its current value. Something like this will do: #include <iterator> template<typename T> struct fib<T>::iterator { using iterator_category = std::input_iterator_tag; using value_type = T; using difference_type = std::ptrdiff_t; using pointer = T*; using reference = T; constexpr iterator() noexcept = default; iterator& operator++() { auto old_next = next; next = next + current; current = old_next; return *this; } iterator operator++(int) { iterator current{*this}; ++(*this); return current; } value_type operator*() const { return current; } bool operator==(const iterator& other) const { return current == other.current && next==other.next; } private: T current= {}; T next = T{} + 1; // Could perhaps be fancier. }; The increment operator does the computation itself, it's the simple iterating algorithm. That's it, here's a working example: #include <cstdint> #include <iostream> int main() { auto is_even = [](auto a) { return a % 2 == 0; }; for (auto v : fib<std::uint64_t>{} | std::ranges::views::filter(is_even) | std::ranges::views::take(10)) std::cout << v << std::endl; return 0; } which outputs: 0 2 8 34 144 610 2584 10946 46368 196418 Of course you won't get very far even with std::uint64_t. But T can be anything numeric enough. One can easily generalize the iterator to hold a stateful functor, likely passed from the range itself, call it during each increment and store the yielded value for dereferencing later. This would be very crude, but simple, way how to at least simulate "yield-based" generators.
70,778,047
70,782,227
Access pixel value of mask using opencv
I got a problem where I need to access pixels of a opencv Mat image container. I use opencv inRange function to create a mask. In that mask I need to check the value of different pixels, but I won't receive the values I expect to receive. // convert image to hsv for better color-detection cv::Mat img_hsv, maskR, maskY, mask1, mask2; cv::cvtColor(image, img_hsv, cv::COLOR_BGR2HSV); // Gen lower mask (0-5) and upper mask (175-180) of RED cv::inRange(img_hsv, cv::Scalar(0, 50, 20), cv::Scalar(5, 255, 255), mask1); cv::inRange(img_hsv, cv::Scalar(175, 50, 20), cv::Scalar(180, 255, 255), mask2); // Merge the masks cv::bitwise_or(mask1, mask2, maskR); after that I try to read the pixel values where I got extremely high values and even nans, but most of them zeros, which is expected as the mask is only black and white if (maskR.at<double>(position.x, position.y) == 255) is there something I'm missing? I tried with double, uchar, int and float when I print the mask, I can clearly see the 0 and 255 entries(no nans or strange numbers), but when I access them with the at() function, I wont get the same results. The coordinates of the pixels should be in the range of the Mat as the dimension of the mask is 1080x1920 and non of the coordinates reach over that. I got the dimension by using cv::size
I finally found the answer to my own question. It works when I use uchar: maskR.at<uchar>(position.x, position.y) == 255 I thought this wouldn't work because printing this with std::cout wouldn't give me an output, but the reason for that is that I forgot to cast uchar so it could be printed in the console
70,778,633
70,778,698
Time/space complexity of string splitting/object creation in c++
I'am struggling to figure out the time complexity of a piece of code that I have that takes a user input from 1 line e.g open 1 0, and splits the input via spaces, then allows the user to create a new 'account' object on the heap. I am thinking it is an O(n^2) operation as it contains 2 while loops, plus an additional function call, this could be completely wrong. int main(){ std::vector <std::string> parameters; std::string userCommand; // Make a new account manager object for a new user AccountManager accounts = AccountManager(); while (userCommand != "exit"){ parameters.clear(); // Clear ready for next command std::cout << std::endl << ">>> "; std::getline(std::cin, userCommand); char* cstr = new char[userCommand.length() + 1]; strcpy(cstr, userCommand.c_str()); char* token; token = strtok(cstr, " "); while (token != nullptr){ parameters.push_back(token); token = strtok(nullptr, " "); } // This calls a function that creates a creates a new object on the heap accounts.openAccount(parameters[1], parameters[2]); } }
The complexity is linear in the total user input length on both space and time. All the individual operations iterate over user input only a constant amount of times, including the inner loop. Therefore with n the total length of user input time the time complexity is Theta(n). Similarly memory is only used to store a constant multiple of the user input length, implying Theta(n) space complexity. This is assuming that the AccountManager operations which you didn't elaborate on are not dominating.
70,778,770
70,779,029
Launching executable in C++
I wish to launch an executable by API call, but I am not sure if one is supposed to check for executable bit using posix APIs before hand. What is best practice in this regard?
All Posix APIs you'll use to launch a process (e.g. execve() and friends) will do any and all required filesystem permissions checks in a context that is atomic and secure (and doing so in user space is neither). Best practice is to simply use the syscalls that are available. As a side note, you can browse the source code of all kinds of tools that invoke the standard fork/exec team you're talking about. For example GNU make. I'm sure there are exceptions somewhere in the wild, but practically speaking I've never seen real software attempt to validate filesystem permissions in user space before calling exec().
70,779,104
70,779,135
How to create a wrapper for `std::make_unique<T>`?
I'd like to create a wrapper for std::unique_ptr<T> and std::make_unique<T> because I think they look ugly and take too long to type. (Yes, I'm that kind of person). I have completed my UniquePtr type alias with no problem but cannot get my MakeUnique to work. It seems to be a bit of a rabbit hole, and was wondering if anyone here might be able to give me a hand with this? What I have so far: template <class T> using UniquePtr = std::unique_ptr<T>; template<typename T, typename... Args> UniquePtr<T> MakeUnique<T>(Args... args) // recursive variadic function { return std::make_unique<T>(args); } Many thanks in advance!
You need to forward properly the values, and you need to expand the pack. First, make it compile: template<typename T, typename... Args> UniquePtr<T> MakeUnique(Args... args) // not recursive { // ^---- no need for <T> when defining function template return std::make_unique<T>(args...); // the ... expands the pack } Then, you need to forward, because args... will copy everything. You want to move rvalues, and copy lvalues: template<typename T, typename... Args> UniquePtr<T> MakeUnique(Args&&... args) { return std::make_unique<T>(std::forward<Args>(args)...); }
70,779,376
70,779,499
How to initialize std::span<const T*>? Problems with const-ness
I am trying to initialize a span<const T*> — that is, a list of pointers to const data. However, the rules for const conversion amongst pointers and span<>'s available constructors are thwarting me. I'm sure there's a way to do it, but I cannot find the right casting/invocation. Aside: I'm actually not using C++20, but tcb::span, which uses the older P0122R7 set of constructors, with (pointer,size) rather than iterators. But I suspect getting something working on C++20 will get me in the right direction. The below example demonstrates what I'm trying to do, and some failed attempts at fixing it: Live link on Godbolt #include<span> #include<vector> #include<iostream> using std::cout; using std::endl; int main() { int a = 0; int b = 1; int c = 2; std::vector<int*> pointers = { &a, &b, &c }; // This declaration does not work; no span<> constructor matches it. std::span<const int*> cspan(&pointers[0], pointers.size()); // This declaration also does not work; the cast is fine, but still no span<> constructor matches. //std::span<const int*> cspan(static_cast<const int *const*>(&pointers[0]), pointers.size()); // This declaration works, but then "cspan" cannot be sorted, since // the pointers themselves are const, and cannot be overwritten. //std::span<const int* const> cspan(&pointers[0], pointers.size()); // Sort the span (by address) // This is the code I want to work. I just need some way to declare 'cspan' properly. std::sort(cspan.begin(), cspan.end()); return 0; } Any ideas?
What's wrong with: #include<span> #include<vector> #include<iostream> using std::cout; using std::endl; int main() { int a = 0; int b = 1; int c = 2; std::vector<int*> pointers = { &a, &b, &c }; std::span<const int*> cspan(const_cast<const int**>(pointers.data()), pointers.size()); std::sort(cspan.begin(), cspan.end()); return 0; }
70,779,554
70,779,922
Error when trying to linking libcurl in static
I'm new in C++ and I got a problem about linking libcurl in static, I downloaded sources and build it myself: ./configure && make install Everything is okay, I write my cmake file, build my program and run, it's working, so I try to link in static and I got many errors about ssl and thread, so I go back in the doc and see that I can build without ssl and thread ( https://curl.se/docs/install.html ), I decided to delete previous installation and rebuild with the next command: ./configure --without-ssl --disable-thread && make install In dynamic linking it's working but same problem in static... and I just cannot find a way to solve the problem. Ine the errors in see "undefined reference to Curl_thread_create" but I built the lib without thread and I included all Curl headers ! I'm lost Here a picture of my workspace picture Thank you for any help
If you link your app with the static libcurl.a, you have to link your app with all other libs that would be linked with the dynamic libcurl.so. You need to build and link your app with following flags: target_compile_options($(CMAKE_PROJECT_NAME) -pthread) target_link_libraries($(CMAKE_PROJECT_NAME) curl pthread z) Perhaps other flags for the errors not shown in the question are required.
70,780,287
70,780,904
Negative indexing of 2d array in C++
In the following code section: // Convolution Operation + Sigmoid Activation for (int filter_dim=0; filter_dim<5; filter_dim++) { for (int i=0; i<28; i++) { for (int j=0; j<28; j++) { max_pooling[filter_dim][i][j] =0; conv_layer[filter_dim][i][j] = 0; sig_layer[filter_dim][i][j] = 0; for (int k=0; k<filter_size; k++) { for (int l=0; l<filter_size; l++) { conv_layer[filter_dim][i][j] = img[-2+i+k][-2+j+l]*conv_w[filter_dim][k][l]; } } sig_layer[filter_dim][i][j] = sigmoid(conv_layer[filter_dim][i][j] + conv_b[filter_dim][i][j]); } } } Because img is a 32-by-32 2d array of type int[][], when i=j=k=l=0, img[-2+i+k][-2+j+l] becomes img[-2][-2] which uses negative indexing on a 2d array, how is this possible? Wouldn't that be index out of bound? Below is the code in main() int main() { read_test_data(); read_train_data(); initialise_weights(); //for (int i=0; i< int epoch = 2000; int num = 0; cout << "Start Training." << endl; for (int i=0; i<epoch; i++) { cout << "Epoch " << i << " done." << endl; for (int j=0; j<batch_size; j++) { num = rand()%60000; int img[32][32]; int vector_y[10]; give_y(label_train[num], vector_y); give_img(data_train[num], img); forward_pass(img); backward_pass(dense_softmax, vector_y, img); update_weights(); //num++; } } and void give_y(int y, int *vector_y) { for (int i=0; i<10; i++) vector_y[i] =0; vector_y[y]=1; } void give_img(int* vec , int img[][32]) { int k=0; for (int i=0; i<32; i++) { for (int j=0; j<32; j++) { if (i<2 || j<2) { img[i][j] = 0; } else { img[i][j] = vec[k]; k++; } } } }
Wouldn't that be index out of bound? Yes it is out of bounds of the array which leads to undefinded behavior. Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. So the first step to make the program correct would be to remove UB(in this case by making sure that index don't go out of bound). Then and only then you can start reasoning about the output of the program. 1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.
70,780,820
70,782,300
How to use bool member function in is_integral_v?
From this cppreference link, is_integral has bool as a member function. How to use it? I could understand other members, and am able to code a simple example as follows. But how to use the bool member function? #include <iostream> #include <type_traits> using namespace std; int main(){ cout << boolalpha; // member constants cout << is_integral_v<int> << endl; // prints true // member functions // operator bool ? // operator() cout << is_integral<float>() << endl; // prints false return 0; }
When you call is_integral<float>(), you are actualy calling the operator bool. The following calls the operator() instead: is_integral<float>()() It can be seen more clear in the following code: std::is_integral<int> x; if (x) { // operator bool std::cout << "true" << std::endl; } std::cout << x << std::endl; // operator bool std::cout << x() << std::endl; // operator() std::cout << std::is_integral<int>()() << std::endl; // operator() std::is_integral<float>() is actually an anonymous object of type std::is_integral<float>.
70,781,635
70,781,930
Making a memory card flipping game in C++
I need some help with this program: Write a program that presents the backs of a number of cards to the player. You should have at least 10 cards. The player selects 2 cards (one at a time), if they match, the player gets a point and the cards remain face up. If they do not match, the cards must turn back over. The game continues until all cards have been turned over. I wrote most of the program but it didn't work out. I don't know how to check if the pairs of cards is match or not but I am trying to do it. Here my code: #include <iostream> #include <string> #include <Windows.h> using namespace std; int main() { int row1, column1, row2, column2, board[2][5]; int choiceBoard[2][5] = { {0,1,2,3,4}, {5,6,7,8,9} }; char displayBoard[2][5] = { {'0','1','2','3','4'}, {'5','6','7','8','9'} }; char displayLetter[2][5] = { {'A','B','C','D','E'}, {'E','D','C','B','A'} }; int firstChoice; int secondChoice; bool playing = true; while (playing) { for (int row = 0; row < 2; row++) { for (int column = 0; column < 5; column++) { cout << "[" << displayBoard[row][column] << "]"; } cout << endl; } cout << "Choose a card to reveal it: "; cin >> firstChoice; for (row1 = 0; row1 < 2; row1++) { for (column1 = 0; column1 < 5; column1++) { if (choiceBoard[row1][column1] == firstChoice) { displayBoard[row1][column1] = displayLetter[row1][column1]; } } } cout << "Choose another card to reveal it: "; cin >> secondChoice; for (row2 = 0; row2 < 2; row2++) { for (column2 = 0; column2 < 5; column2++) { if (choiceBoard[row2][column2] == secondChoice) { displayBoard[row2][column2] = displayLetter[row2][column2]; } } } if (board[row1][column1] == board[row2][column2]) { cout << "Match!" << endl; Sleep(2000); } else { cout << "Card do not match!" << endl; Sleep(1000); } system("cls"); if (firstChoice == secondChoice) { cout << "Error..." << endl; playing = false; } } return 0; }
I don't know what these boards' functions are, but if you want to judge if the selected pair is match, you can try this: if (displayLetter[firstChoice / 5][firstChoice % 5] == displayLetter[secondChoice / 5][secondChoice % 5]) { cout << "Match!" << endl; Sleep(2000); } Then you can change the display content, I don't think some of the for-loops are necessary.
70,781,838
70,782,561
c++ virtual inheritance doesn't work, how do I use the multiple parents' members?
Example of using virtual inheritance class AA { public: AA() { cout << "AA()" << endl; }; AA(const string& name, int _a):n(name),a(_a) {}; AA(const AA& o) :n(o.n), a(o.a) {}; virtual ~AA() { cout << "~AA()" << endl; }; protected: int a = 0; std::string n; }; class A1 : public virtual AA { public: A1(const string& s) : AA(s, 0){} }; class A2 : public virtual AA { public: A2(const string& s) : AA(s, 0) {} }; class B : public A1, public A2 { public: B(const string& a1, const string& a2) : A1(a1), A2(a2){} void test() { cout << A1::n << endl; cout << A2::n << endl; } }; void test() { B b("abc", "ttt"); b.test(); } Ideally, A1::n would be "abc" and A2::n would be "ttt". But they are both empty. Only AA() will be called once during the entire process. What did I do wrong?
The result is correct, while the real reason is when you are using virtual inheritance, D ctor first uses AA's default ctor, n is not assigned. If you want to use AA(name, a), you need to explicitly use that in D.
70,781,863
70,784,310
Is it possible to increment setw?
I need to display something that looks like: / - / / - / / / - I currently have the following which does not print the slashes properly. for (int i = 1; i <= numberOfDolls; i++) { for(int j = 1; j <= i; j++) cout << setw(numberOfDolls) << '/' << endl; cout << "-" << endl; } I was thinking of using setw() to increment the slashes. Is this possible?
I am not sure about your doubt but you will get desired output using following: for (int i = 1; i <= numberOfDolls; i++) { for(int j = 1, n=numberOfDolls; j <= i; j++) cout << setw(n--) << '/' << endl; cout <<setw(numberOfDolls-1)<< "-" << endl; }
70,782,051
70,782,100
unique_ptr inside a variant. Is it safe to use?
Id like to ask, is safe having a variant like this? struct A { unique_ptr<T> anything; }; struct B { int x = 0; int y = 0; }; variant<A, B> myVar; myVar = ... A object; myVar = ... B object; myVar = ... another A object; Would the std::unique_ptr destructor be invoked for all compilers? The idea would be to create an std::array of variant<A, B> to use it in a FIFO. It seems working fine here in Visual Studio, but I ask because I read this from cppreference.com/variant, and I'm not sure if I understood it fully: As with unions, if a variant holds a value of some object type T, the object representation of T is allocated directly within the object representation of the variant itself. Variant is not allowed to allocate additional (dynamic) memory.
The paragraph you quoted is a guarantee by the standard; As with unions, if a variant holds a value of some object type T, the object representation of T is allocated directly within the object representation of the variant itself. Variant is not allowed to allocate additional (dynamic) memory. It means std::variant is not allowed to utilize dynamic allocation for the objects that the variant holds. It's a guarantee by the standard. If you have a variant object with Foo, Foo is in the memory of the variant and not in a dynamically allocated object somewhere else. Which means it is safe to use dynamic allocation (i.e. unique_ptr) within a variant. All destructors are properly called when they need to be called.
70,782,158
70,782,833
How to read paragraphs from a file while avoiding the blank space between them into an array?
I have been trying to figure this out. I'm very new to C++. I have tried using this: (what modifications would be needed?) while(!openFile.fail()) { getline(openFile,myArray[size]) } My array size is the same as the number of paragraphs. However, I can't figure out how to consider the paragraphs as one element of the array. Edit [How I did it]: while(!openFile.fail()) // while no errors keep going. { // then i needed a for loop to iterate [size of array] times. for ( int i = 0; i < sizzArr; i++) { getline(tempFile, copyDataF); // this getline gets my first line from the data file into our copyDataF. while (copyDataF.length() != 0) // when what we copied is not empty { arr[i] = arr[i] + copyDataF + "\n"; getline(tempFile, copyDataF); /* assuming next line is blank, our while loop will stop, the iteration will repeat till end of file (+ depends on the for loop). */ } } [ thank you everyone who tried to help as i admit my question wasn't clear enough ]
I'm not entirely sure what step you're having trouble with, but if I understand correctly. You have a file of some kind that you want to read from and a std::string array initialized to have size equaling the number of lines in the file. You can easily open a file with <ifstream> using open() and then read the file line by line with std::getline(), adding each line to the resultant array. If you want to perform any further logic (searching for spaces in a line, whatever else) this should be enough to get you headed in the right direction. For context, the ./foo.txt file contains 3 newline separated strings of text. #include <iostream> #include <ifstream> using namespace std; int main() { ifstream file; string line; file.open("./foo.txt", std::ios_base::in); string lines[3]; int i = 0; if (file.is_open()) { // begin reading the file line by line while (std::getline(file, line)) { cout << "line: " << line << endl; lines[i] = line; i++; } } else { cout << "error opening file" << endl; } cout << "printing array" << endl; for (int j = 0; j < 3; j++) { cout << lines[j] << endl; } return 0; }
70,782,217
70,782,235
Qt5 slot lambda why captured local variable is random for the first time lambda is called
In the following code, I think p2 should print 10. But in fact it prints random value. The I starts to understand why it is not 10, with the following (1)-(3) thougths. { int m = 10; // local var m qDebug() << "m0: " << &m; connect(btn2, &QPushButton::clicked, this, [&]() { qDebug() << "m2: " << &m; qDebug() << "p2 " << m; m = 20; qDebug() << "p22 " << m; }); // captured var m } output: m0: 0x8ff8ac p0 10 m2: 0x8ff8ac p2 11974204 p22 20 m2: 0x8ff8ac p2 20 p22 20 (1). The first time lambda is called, its captured var m has random value. I think this may because local var m is a local variable, and it is on stack memory, which is released after }, and it is random thereafter. (2). After captured m is assigned 20 inside lambda, when it is called a second time, m remains 20. Which is against what I think in (1), because when quits lambda function, m memory should be released, and thereafter random value again. (3).[&] enables lambda to access memory that is released, isn't it dangerous? Based on my above thoughts, my question would be why captured m is not 10 (what p2 prints)? why a released memory could be accessed and modified, isn't it dangerous? why a second visit of lambda, m is not random?
Because you capture it by reference. Once the function ends, so does the life-time of all its local variables. The local variables cease to exist. Any reference or pointer to them will become invalid. Using such references or dereferencing such pointers will lead to undefined behavior. The life-time of all variables captured by reference must be at least as long as the life-time of the lambda itself.
70,782,546
70,791,991
Merge and/or Override flags of different configure presets in CMakePresets.json
I have two configure presets in my CMakePresets.json were I would like to merge the flags of the inherit configurePresets (gcc) with the other preset (gcc-arm-embedded) Here is a simplified version: "configurePresets": [ { "name": "gcc", "hidden": true, "cacheVariables": { "CMAKE_CXX_FLAGS": "-Wall -Wextra", "CMAKE_BUILD_TYPE": "Release" } }, { "name": "gcc-arm-embedded", "hidden": true, "inherits": ["gcc"], "cacheVariables": { "CMAKE_CXX_FLAGS": "-ffunction-sections -fdata-sections", "CMAKE_EXE_LINKER_FLAGS": "-mcpu=cortex-m7 -mthumb", "CMAKE_BUILD_TYPE": "MinSizeRel" } }, { "name": "embedded", "inherits": ["gcc", "gcc-arm-embedded"] } ] The problem is, if I use the presets embedded the resulting CMAKE flags are: CMAKE_CXX_FLAGS: "-Wall -Wextra" CMAKE_EXE_LINKER_FLAGS: "-mcpu=cortex-m7 -mthumb", CMAKE_BUILD_TYPE: "Release" My goal is this: CMAKE_CXX_FLAGS: "-Wall -Wextra -ffunction-sections -fdata-sections" CMAKE_EXE_LINKER_FLAGS: "-mcpu=cortex-m7 -mthumb", CMAKE_BUILD_TYPE: "MinSizeRel" Is this somehow possible with CMakePresets?
First, simplify the inherits entry to: "inherits": ["gcc-arm-embedded"] The resolution order works left to right, never overwriting, but since gcc-arm-embedded inherits from gcc already, there's no need to specify both. So that gets you to this: CMAKE_CXX_FLAGS: "-ffunction-sections -fdata-sections" CMAKE_EXE_LINKER_FLAGS: "-mcpu=cortex-m7 -mthumb", CMAKE_BUILD_TYPE: "MinSizeRel" Now let's add a base preset: { "name": "base", "hidden": true, "cacheVariables": { "CMAKE_CXX_FLAGS": "$env{CXX_WARNINGS} $env{CXX_OPT}", "CMAKE_BUILD_TYPE": "Release" } }, Then make gcc inherit from base and remove the cacheVariables section. Instead, set: "environment": { "CXX_WARNINGS": "-Wall -pedantic" } and in gcc-arm-embedded additionally set: "environment": { "CXX_OPT": "-ffunction-sections -fdata-sections" } The end result is this: { "version": 3, "cmakeMinimumRequired": { "major": 3, "minor": 21, "patch": 0 }, "configurePresets": [ { "name": "base", "hidden": true, "cacheVariables": { "CMAKE_CXX_FLAGS": "$env{CXX_WARNINGS} $env{CXX_OPT}", "CMAKE_BUILD_TYPE": "Release" } }, { "name": "gcc", "inherits": ["base"], "hidden": true, "environment": { "CXX_WARNINGS": "-Wall -pedantic" } }, { "name": "gcc-arm-embedded", "hidden": true, "inherits": ["gcc"], "cacheVariables": { "CMAKE_EXE_LINKER_FLAGS": "-mcpu=cortex-m7 -mthumb", "CMAKE_BUILD_TYPE": "MinSizeRel" }, "environment": { "CXX_OPT": "-ffunction-sections -fdata-sections" } }, { "name": "embedded", "inherits": ["gcc-arm-embedded"] } ] }
70,782,552
70,782,820
What is wrong with this code? The answer should be 24 for this question right?
What is wrong with this code? The answer should be 24 for this question right? int t; vector<int>arr={24,434}; for(int i=arr.size()-1;i>=(arr.size()-2);i--) { t=i; } cout<<arr[t];
This loop for(int i=arr.size()-1;i>=(arr.size()-2);i--) is an infinite loop. When i is equal to 0 it is decremented due to the third expression of the loop and becomes equal to -1. And then in this condition i>=(arr.size()-2) as the operand arr.size()-2 has unsigned integer type with the rank not less than the rank of an object of the type int then due to the usual arithmetic conversions the expression i is converted to the unsigned integer type that corresponds to the type of the expression arr.size()-2 and becomes a very big value due to promoting the bit sign. That is in this expression i>=(arr.size()-2) the left operand can not be a negative value. In fact this loop for(int i=arr.size()-1;i>=(arr.size()-2);i--) does not make a sense because in any case there can be no more than one iteration.
70,782,570
70,785,675
Dart/Flutter FFI: Convert List to Array
I have a struct that receives an array of type Float from a C++ library. class MyStruct extends Struct{ @Array.multi([12]) external Array<Float> states; } I am able to receive data and parse it in Dart. Now I want to do the reverse. I have a List<double> which I want to assign to this struct and pass to C++. The following cast fails at run time. myStructObject.states = listObject as Array<Float>; Neither Array class, nor List class has any related methods. Any idea on this?
There's no way to get around copying elements into FFI arrays. for (var i = 0; i < listObject.length; i++) { my_struct.states[i] = listObject[i]; } This may seem inefficient, but consider that depending on the specialization of listObject, the underlying memory layout of the data may differ significantly from the contiguous FFI layout, and so a type conversion sugar provided by Dart would likely also need to perform conversions on individual elements anyways (as opposed to just performing a single memcpy under the hood). One possibility for closing the convenience gap would be to define an extension method. For example: extension FloatArrayFill<T> on ffi.Array<ffi.Float> { void fillFromList(List<T> list) { for (var i = 0; i < list.length; i++) { this[i] = list[i] as double; } } } Usage: my_struct.states.fillFromList(list); Note that a separate extension method would be need to be defined for each ffi.Array<T> specialization you want to do this for (Array<Uint32>, Array<Double>, Array<Bool>, etc.). This is due to the [] operator being implemented through a separate extension method for each of these type specializations internally.
70,782,643
70,783,249
warning: '*' in boolean context, suggest '&&' instead [-Wint-in-bool-context]?
i've this code (which is pretty all "float"): #define sincf(x) (x == 0.0f) ? (1.0f) : (sinf(M_PI * x) / (M_PI * x)) // ... for (int i = 0; i < num_taps; i++) proto[i] = 2.0f * f * sincf(2.0f * f * (i - m / 2.0f)); // ... why gcc says warning: '' in boolean context, suggest '&&' instead [-Wint-in-bool-context]* for the second "*"? f is float proto is *float i and m are int
After the macro has been substituted, this part 2.0f * f * sincf(2.0f * f * (i - m / 2.0f)); becomes 2.0f * f * (2.0f * f * (i - m / 2.0f) == 0.0f) ? ... and according to operator precedence, the multiplication 2.0f * f * condition will be done before checking if the condition is true (with ?). Like so: (2.0f * f * (2.0f * f * (i - m / 2.0f) == 0.0f)) ? ... The quick fix: #define sincf(x) (((x) == 0.0f) ? (1.0f) : (sinf(M_PI * (x)) / (M_PI * (x)))) (x) == 0.0f will rarely be true but since it's only used to avoid division by zero, that's probably fine. Now, this could easily be rewritten as a function and I suggest doing that. Example: template<class T> T sinc(T x) { if(x == T{}) return {1}; // avoid division by zero auto pix = static_cast<T>(M_PI) * x; return std::sin(pix) / pix; } One could also cast x to double if T is an integral type. Here's a C++20 version of that: #include <concepts> // std::integral #include <numbers> // std::numbers::pi_v template<class T> T sinc(T x) { if(x == T{}) return 1; // avoid division by zero // C++20 added some constants to the standard library: auto pix = std::numbers::pi_v<T> * x; return std::sin(pix) / pix; } double sinc(std::integral auto x) { return sinc<double>(x); }
70,782,888
70,783,876
Strange errors of compiling pcl1.8 with cuda 11.3
System: cuda 11.3, gcc 7.5, boost 1.65.1, pcl 1.8.0 When I compile code that uses PCL library, it shows the following error /usr/include/pcl-1.8/pcl/io/file_io.h(264): error: namespace "boost" has no member "numeric_cast" /usr/include/pcl-1.8/pcl/io/file_io.h(264): error: type name is not allowed /usr/include/pcl-1.8/pcl/io/file_io.h(280): error: namespace "boost" has no member "numeric_cast" /usr/include/pcl-1.8/pcl/io/file_io.h(280): error: type name is not allowed /usr/include/pcl-1.8/pcl/io/file_io.h(346): error: namespace "boost" has no member "iequals" /usr/include/pcl-1.8/pcl/io/file_io.h(372): error: namespace "boost" has no member "iequals" /usr/include/pcl-1.8/pcl/io/pcd_io.h(485): error: name followed by "::" must be a class or namespace name /usr/include/pcl-1.8/pcl/io/pcd_io.h(493): error: name followed by "::" must be a class or namespace name I looked into the file_io.h, found that the related code is <pcl/io/boost.h>. In this file, the header <boost/numeric/conversion/cast.hpp> contains the numeria_cast function, obviously this header is not included. Is this error related to the macro __CUDACC__? How do I solve this issue? /usr/include/pcl-1.8/pcl/io/boost.h is: #ifndef _PCL_IO_BOOST_H_ #define _PCL_IO_BOOST_H_ #if defined __GNUC__ # pragma GCC system_header #endif #ifndef __CUDACC__ //https://bugreports.qt-project.org/browse/QTBUG-22829 #ifndef Q_MOC_RUN #include <boost/version.hpp> #include <boost/numeric/conversion/cast.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/condition.hpp> #include <boost/thread.hpp> #include <boost/thread/thread.hpp> #include <boost/filesystem.hpp> #include <boost/bind.hpp> #include <boost/cstdint.hpp> #include <boost/function.hpp> #include <boost/tuple/tuple.hpp> #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include <boost/mpl/fold.hpp> #include <boost/mpl/inherit.hpp> #include <boost/mpl/inherit_linearly.hpp> #include <boost/mpl/joint_view.hpp> #include <boost/mpl/transform.hpp> #include <boost/mpl/vector.hpp> #include <boost/algorithm/string.hpp> #ifndef Q_MOC_RUN #include <boost/date_time/posix_time/posix_time.hpp> #endif #if BOOST_VERSION >= 104700 #include <boost/chrono.hpp> #endif #include <boost/tokenizer.hpp> #include <boost/foreach.hpp> #include <boost/shared_array.hpp> #include <boost/interprocess/sync/file_lock.hpp> #if BOOST_VERSION >= 104900 #include <boost/interprocess/permissions.hpp> #endif #include <boost/iostreams/device/mapped_file.hpp> #define BOOST_PARAMETER_MAX_ARITY 7 #include <boost/signals2.hpp> #include <boost/signals2/slot.hpp> #endif #endif #endif // _PCL_IO_BOOST_H_
Right, I solved it by using normal gcc compiler... DONT USE NVCC!
70,782,966
70,783,451
Why does requires-expression behave differently in template and not-template for checking private member access?
In the following code class A has a private member function f. I want to write a static assertion that will check whether this function is accessible from the current context (as was suggested in the comment to this question). There are 3 similar cases all based on requires-expression: class A{ void f(); }; // #1: accepted by all static_assert( ![](auto x){ return requires(decltype(x) a){ a.f(); }; }(A{}) ); // #2: rejected by Clang: static_assert( ![](auto){ return requires(A a){ a.f(); }; }(nullptr) ); // #3: rejected by all static_assert( ![](void*){ return requires(A a){ a.f(); }; }(nullptr) ); The case #3 (and #2 in Clang) is rejected with the error: error: 'f' is a private member of 'A' Demo: https://gcc.godbolt.org/z/Mxs4P7x8s Why does requires-expression behave differently in template and not-template (cases #1 and #3)? Which compiler is right in #2?
Whilst https://eel.is/c++draft/expr.prim.req.general#1 describes that A requires-expression provides a concise way to express requirements on template arguments the grammar of a requires-expression requires-expression: requires requirement-parameter-list(opt) requirement-body requirement-body: { requirement-seq } requirement-seq: requirement requirement requirement-seq requirement: simple-requirement [...] simple-requirement: expression ; // A simple-requirement asserts the validity of an expression. allows requires-expressions containing arbitrary expressions that do not necessarily depend on template arguments, meaning the following is well-formed: constexpr bool f() { return requires(int a) { a; }; } constexpr bool g() { return requires { 0; }; } static_assert(f()); static_assert(g()); Thus, for a requires-expression that is declared outside of a templated entity, the same rules as for any expression applies, and #3 is thus correctly rejected by all compilers (access checking control is not waived in the context of expressions in requires-expressions). #1 is also correctly implemented by all compilers, as per https://eel.is/c++draft/expr.prim.req.general#5.sentence-2: The substitution of template arguments into a requires-expression may result in the formation of invalid types or expressions in its requirements or the violation of the semantic constraints of those requirements. In such cases, the requires-expression evaluates to false; it does not cause the program to be ill-formed. ... as a.f(); in the constraint expression for the generic a substituted as being of type A results in an invalid expression, as f() is private and not visible. Finally, #2 is IFNDR as per https://eel.is/c++draft/expr.prim.req.general#5.sentence-6: If the substitution of template arguments into a requirement would always result in a substitution failure, the program is ill-formed; no diagnostic required. We could likewise argue that it is IFNDR as per https://eel.is/c++draft/temp.res.general#6.4: The program is ill-formed, no diagnostic required, if: [...] a hypothetical instantiation of a template immediately following its definition would be ill-formed due to a construct that does not depend on a template parameter, or Thus, #2 is correctly implemented by all compilers, but it's arguably always nice when compilers actually do diagnose IFNDR violations, so a usability star for Clang.
70,783,028
70,783,471
Cast uint8_t-array to readable format
I have this code, which receives a row of byte-values, inserted in an array. How can I show the content "readable" and not like this: R$⸮⸮>⸮⸮⸮ Here's the relevant code: // Read data from UART. uint8_t myData[8]; String myDataString = ""; int length = 0; ESP_ERROR_CHECK(uart_get_buffered_data_len(uart_num, (size_t*)&length)); length = uart_read_bytes(uart_num, myData, length, 100); if (length > 0) { for (int i=0; i<length; i++) { //SerialMon.write(myData[i]); myDataString += myData[i]+","; } SerialMon.println(myDataString); // should be something like "82,36,18,43,129,255,255,255" } I believe the problem is, that a byte value like 82 in ASCII corresponds to the letter 'R' when displaying it as a character. Is there an easy way to convert the values, so that an element like 82 will show up as "82" instead... or even better: as HEX?
You are correct with your assumption that myData[i] gets interpreted as ASCII-code, but you can easily convert it into a HEX-string as follows: myDataString += String(myData[i], HEX);
70,783,449
70,783,627
Question about Bitwise Shift in Microsoft C++
I am doing the following bitwise shift in Microsoft C++: uint8_t arr[3] = {255, 255, 255}; uint8_t value = (arr[1] << 4) >> 4; The result of these operations confused me quite a bit: value = 255 However, if I do the bitwise shift separately: value = (arr[i] << 4); value = value >> 4; the answer is different and makes much sense: value = 15 Can someone explain to me why this happens? I am familiar with the concepts of bitwise shift, or so I believed... Thanks in advance! (P.S.: It seems g++ will have the same behavior. I am probably missing some important concepts with bitwise shift. Any help is greatly appreciated!)
Expression (arr[1] << 4) will implicitly promote the value of arr[1] to type unsigned int before applying the shift operation, such that the "intermediate" result will not "loose" any bits (cf, for example, the explanation in implicit conversions). However, when you write value = (arr[i] << 4);, then this "intermediate" result will be converted back to uint_8, and in this step bits get cut off. See the difference when you write uint8_t value = ((uint8_t)(arr[1] << 4)) >> 4;
70,783,542
70,788,205
Preprocessor definitions based on visual studio configuration type
I am working on a C++ project in Visual Studio 2019, which should have the ability to be compiled as an executable and as a DLL. It is legacy code and contains the preprocessor flags AS_EXE and AS_DLL, which is presumably the flags I need to set. I just don't know how to do this based on different values in Project -> Properties -> Configuration Properties -> General -> Configuration Type. I would like the values Dynamic Library (.dll) and Application (.exe) to map to the two preprocessor definitions, AS_DLL and AS_EXE respectively. I have looked around on Google the last couple of days, but without luck. It would be nice if it could be done similarly to when switching between debug and release, but I sense that it'll be a bit more complex. Can this even be achieved? And if so, how would I go about doing it?
You can use Condition attribute of ItemDefinitionGroup node in your .vcxproj. <ItemDefinitionGroup Condition="'$(Configuration)'=='MyConfigForDLL'"> <ClCompile> <PreprocessorDefinitions>AS_DLL;%(PreprocessorDefinitions)</PreprocessorDefinitions> ... </ClCompile> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)'=='MyConfigForEXE'"> <ClCompile> <PreprocessorDefinitions>AS_EXE;%(PreprocessorDefinitions)</PreprocessorDefinitions> ... </ClCompile> </ItemDefinitionGroup> Or, from GUI:
70,783,880
70,783,952
Unit tests for C++ criterion
I'm trying to make unit tests with criterion for my C++ code but I can't figure out how to test a function that only print and do not return anything. Here's what I tried: //the function to test #include <iostream> #include <fstream> void my_cat(int ac, char **av) { if (ac <= 1) std::cout << "my_cat: Usage: ./my_cat file [...]" << std::endl; for (unsigned i = 1; i < ac; i += 1) { std::ifstream file (av[i]); if (file.fail()) { std::cout << "my_cat: "; std::cout << av[i]; std::cout << ": No such file or directory" << std::endl; } else if (file.is_open()) { std::cout << file.rdbuf() << std::endl; } file.close(); } } //the test #include <criterion/criterion.h> #include <criterion/redirect.h> void my_cat(int ac, char **av); Test(mycat, my_cat) { char *av[] = {"./my_cat", "text.txt"}; my_cat(2, av); } But now that I'm here I don't know what to use to check if the print is correct.
With gtest, I think this can help you testing::internal::CaptureStdout(); std::cout << "My test"; std::string output = testing::internal::GetCapturedStdout(); refer from : How to capture stdout/stderr with googletest?
70,784,182
70,784,444
Where exactly are variables stored while vectors store in RAM?
I used this and compiled it: #include <iostream> #include <string> #include <vector> int main() { std::vector<std::string> articles (119999999,"ads"); std::cout << articles[1]; getchar(); return 0; } Then a memory error occurred that the memory is full (because no loss of information occurred). I opened the task manager and then I opened the program again. The program was consuming 250 megabytes, then my computer suddenly shutdown. I asked myself why when I declare many variables and arrays, there is no memory error. So much so that I wrote a program to create a text file and then write thousands of variables and then I translated that file and the program opened normally! Where are variables stored? And are vectors stored in RAM only?
sizeof(std::string) is typically 32 bytes. Even with short string optimisation, the memory request is a contiguous block of 119999999 * 32 bytes. That's of the order of 4Gb and beyond the capability of your computer. If you require the storage of duplicate strings then consider std::reference_wrapper as the vector element type.
70,784,323
70,785,115
What data type should I use in cv::Mat.at<data_type> when using CV_8SC3, CV_16FC3, CV_16FC1?
When looing through the image and to index the (i, j) , OpenCV provides the method at in cv::Mat. In order to get the correct value of that pixel we need to specify data type carefully ,or we might get some unexpected value. For example, if you use CV_16SC3 to create cv::Mat like below : cv::Mat img(h, w, CV_16SC3, cv::Scalar(-32, -64, -64)); When indexing the value you should use cv::Vec3s like : img.at<cv::Vec3s>(i, j)[c] If you use soem other type like img.at<cv::Vec3f> you would get some wrong value. Now we know the importance of filling right data type, the table below is all I know what data type to put in to get correct value . CV_8UC3 -> cv::Vec3b CV_8UC1 -> uchar CV_8SC3 CV_8SC1 -> char CV_16UC3 -> cv::Vec3w CV_16UC1 -> ushort CV_16SC3 -> cv::Vec3s CV_16SC1 -> short CV_32SC3 -> cv::Vec3i CV_32SC3 -> int CV_64FC3 -> cv::Vec3d CV_64FC1 -> double CV_32FC3 -> cv::Vec3f CV_32FC1 -> float CV_16FC3 -> CV_16FC1 -> I would like to know for CV_8SC3, CV_16FC3, CV_16FC1, what data type should I write in order to get the correct value ? Thanks in advance !
You can define your own specialization on your demand. cv::Vecxx are just a bunch of shorter aliases for for the most popular specializations of Vec<T,n> So: for CV_8SC3, you might use cv::Vec<char, 3>, for CV_16FC3, you might use cv::Vec<cv::float16_t, 3>. for CV_16FC1, you might use cv::Vec<cv::float16_t, 1>. Besides, if you just want to iterate through a cv::Mat, there are actually many ways to do so, for example, the at method have this overloaded version: template<typename _Tp > const _Tp& cv::Mat::at (int i0, int i1, int i2) const And i hope this official document will help you more: https://docs.opencv.org/4.x/db/da5/tutorial_how_to_scan_images.html
70,784,593
70,823,620
Confused with some Vulkan concept
i have some few questions about Vulkan concepts. 1. vkCmdBindDescriptorSets arguments // Provided by VK_VERSION_1_0 there is prototype: void vkCmdBindDescriptorSets( VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t firstSet, uint32_t descriptorSetCount, const VkDescriptorSet* pDescriptorSets, uint32_t dynamicOffsetCount, const uint32_t* pDynamicOffsets); i want to know the usage of descriptorSetCount and pDescriporSets, pipeline use only one VkDescriptorSet in a drawcall,but provide multiply same layout VkDescriptorSet means what? 2. glsl uniform layout layout(set=0,binding =0) uniform UniformBufferObject { mat4 view; mat4 projection; vec3 position_camera; }ubo; what does set means?
Understanding Vulkan uniform layout's 'set' index vkCmdBindDescriptorSets update the current descriptorSet array. the index of set define your shader use the one of array[index].
70,784,873
70,784,960
C++ Using Boost logging with Cmake fails to compile
I am trying to compile C++ using boost logging library with CMake. Heres a simple example my CPP file - logtests.cpp #include <iostream> #include <boost/log/trivial.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/expressions.hpp> namespace logging = boost::log; void init_logging() { logging::add_file_log("sample.log"); logging::core::get()->set_filter ( logging::trivial::severity >= logging::trivial::info ); } int main(int, char*[]) { init_logging(); BOOST_LOG_TRIVIAL(trace) << "This is a trace severity message"; BOOST_LOG_TRIVIAL(debug) << "This is a debug severity message"; BOOST_LOG_TRIVIAL(info) << "This is an informational severity message"; BOOST_LOG_TRIVIAL(warning) << "This is a warning severity message"; BOOST_LOG_TRIVIAL(error) << "This is an error severity message"; BOOST_LOG_TRIVIAL(fatal) << "and this is a fatal severity message"; std::cin.get(); return 0; if I use g++ with the following arguments it compiles and runs without an issue. #g++ includes/screwAround/logtest.cpp -DBOOST_LOG_DYN_LINK -o logtest -lboost_log -lboost_system -lboost_thread -pthread But if I use this CMakeLists.txt it fails. cmake_minimum_required(VERSION 3.6.3) project(logtest) # Enable C+11 #set(CMAKE_CXX_STANDARD 11) ADD_DEFINITIONS(-DBUILD_SHARED_LIBS=ON) # Library source files ADD_DEFINITIONS(-DBOOST_LOG_DYN_LINK) FIND_PACKAGE(Boost 1.67 COMPONENTS log thread system log_setup filesystem REQUIRED) set(CMAKE_THREAD_PREFER_PTHREAD TRUE) set(THREADS_PREFER_PTHREAD_FLAG TRUE) find_package(Threads REQUIRED) INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR}) # Create example executable add_executable(logtestcase logtest.cpp) TARGET_LINK_LIBRARIES(logtestcase ${Boost_LOG_LIBRARY} ${CMAKE_THREAD_LIBS_INIT} ) with this error: /usr/bin/ld: CMakeFiles/logtestcase.dir/logtest.cpp.o: undefined reference to symbol '_ZN5boost6detail12get_tss_dataEPKv' /usr/bin/ld: //lib/arm-linux-gnueabihf/libboost_thread.so.1.67.0: error adding symbols: DSO missing from command line collect2: error: ld returned 1 exit status make[2]: *** [CMakeFiles/logtestcase.dir/build.make:85: logtestcase] Error 1 make[1]: *** [CMakeFiles/Makefile2:76: CMakeFiles/logtestcase.dir/all] Error 2 make: *** [Makefile:84: all] Error 2 The root cause seems to be that CMake won't include the Threads package, I've tried added Threads::Threads to the target_link_libraries like shown here without success.
If you want to use dynamic multi-threaded Boost libraries, you need to set the Boost_USE_STATIC_LIBS and Boost_USE_MULTITHREAD flags before looking for Boost: set(Boost_USE_STATIC_LIBS OFF) set(Boost_USE_MULTITHREAD ON) FIND_PACKAGE(Boost log log_setup) These flags are documented. I also recommend you use the Boost::<component> imported targets when linking: TARGET_LINK_LIBRARIES(logtestcase Boost::log)
70,784,886
70,787,564
How can I compare system_clock::now() to a local time in c++20?
I am testing a library like follows: std::chrono::system_clock::time_point FromDateTime(const DateTime& dateTime) { std::tm tm{}; tm.tm_year = dateTime.Year - 1900; tm.tm_mon = dateTime.Month - 1; tm.tm_mday = dateTime.Day; tm.tm_hour = dateTime.Hour; tm.tm_min = dateTime.Minute; tm.tm_sec = dateTime.Second; const auto& time = std::mktime(&tm); const auto& timePoint = std::chrono::system_clock::from_time_t(time); return timePoint; } TEST_F(MyLibraryFixture, GetDateTime) { // Arrange const auto& now = std::chrono::system_clock::now(); // Act const auto& actual = _testee->GetDateTime(); // Assert const auto& timeDiscrepanceInSec = std::chrono::duration_cast<std::chrono::seconds>(FromDateTime(actual) - now); ASSERT_TRUE(timeDiscrepanceInSec.count() < 10); } The DateTime type is just a raw struct with the above used fields. The call _testee->GetDateTime(); gives a DateTime struct back and the date time is actually local time. For some reason inherent to the library I am testing, I need to compare the local time with the time it is now. My code above seems to be working fine, I "hope" it will still work when we get back to Summer time. Now, c++20 exposes a lot of date time utilities. I have browsed the documentation, I have tried some stuff, but I was not able to come up with a reliable counterpart to the above snippet. Is it any possible (I mean, without using std::mktime and the strange std::tm)? The closest I was able to come is this, but it is still wrong (I get a discrepancy of one hour): std::chrono::time_point<std::chrono::local_t, std::chrono::seconds> FromDateTime(const DateTime& dateTime) { const auto& d = std::chrono::year_month_day(std::chrono::year(dateTime.Year), std::chrono::month(dateTime.Month), std::chrono::day(dateTime.Day)); const auto& t = std::chrono::hours(dateTime.Hour) + std::chrono::minutes(dateTime.Minute) + std::chrono::seconds(dateTime.Second); const auto& dt = std::chrono::local_days(d) + t; return dt; } TEST_F(MyLibraryFixture, GetDateTime) { // Arrange const auto& now = std::chrono::utc_clock::now(); // Act const auto& actual = _testee->GetDateTime(); // Assert const auto& timeDiscrepanceInSec = std::chrono::duration_cast<std::chrono::seconds>(FromDateTime(actual).time_since_epoch() - now.time_since_epoch()); ASSERT_TRUE(timeDiscrepanceInSec.count() < 10); }
Here's the equivalent C++20 code to your first version of FromDateTime: std::chrono::system_clock::time_point FromDateTime(const DateTime& dateTime) { using namespace std::chrono; auto local_tp = local_days{year{dateTime.Year}/dateTime.Month/dateTime.Day} + hours{dateTime.Hour} + minutes{dateTime.Minute} + seconds{dateTime.Second}; zoned_time zt{current_zone(), local_tp}; return zt.get_sys_time(); } You were on the right track with creating a local_time using local_days. There's no need to explicitly name the year_month_day type. This is generated for you using the / notation. Once you have the local time, you can associate it with your computer's local time zone by constructing a zoned_time with current_zone() and the local_time. Then you can extract the sys_time out of the zoned_time. The sys_time is a time_point<system_clock, seconds> (seconds-precision system_clock::time_point), which is UTC (excluding leap seconds). And this implicitly converts to the return type: system_clock::time_point. If desired, you could interpret the local_time with respect to some other time zone, rather than your computer's local time zone. For example: zoned_time zt{"America/New_York", local_tp}; In general, zoned_time is a convenience type used to translate between local_time and sys_time.
70,785,189
70,785,575
How to push pair from priority queue into a 2D array?
I am doing a leetcode problem, and I am required to return a 2d array of results. But I am using a priority queue for that and am unable to move elements to a 2d array. I am not able to come up with a syntax for this. The push_back(), is not working when I try to push the pair in a 2d array. here is the link to the problem Code - class Solution { public: vector<vector<int>> kClosest(vector<vector<int>>& p, int k) { vector<vector<int>>closest; //pairp; priority_queue<pair<int,pair<int,int>>>heap; for(int i = 0; i < p.size(); i++){ heap.push({p[i][0] * p[i][0] + p[i][1]*p[i][1], {p[i][0],p[i][1]}}); } if(heap.size() > k){ heap.pop(); } while(heap.size() > 0){ pair<int,int>ptr = heap.top().second; //want to add the statement to copy elements to closest[][] here heap.pop(); } return closest; } }; Error message on adding, closest.push_back(ptr); Line 22: Char 21: error: no matching member function for call to 'push_back' closest.push_back(ptr); ~~~~~~~~^~~~~~~~~ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1184:7: note: candidate function not viable: no known conversion from 'pair<int, int>' to 'const std::vector<std::vector<int, std::allocator>, std::allocator<std::vector<int, std::allocator>>>::value_type' (aka 'const std::vector<int, std::allocator>') for 1st argument push_back(const value_type& __x) ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1200:7: note: candidate function not viable: no known conversion from 'pair<int, int>' to 'std::vector<std::vector<int, std::allocator>, std::allocator<std::vector<int, std::allocator>>>::value_type' (aka 'std::vector<int, std::allocator>') for 1st argument push_back(value_type&& __x) ^ 1 error was generated.
// if closet should be your answer then its size will be k /* Here we tell how many rows the 2D vector is going to have. And Each row will contain a vector of size 2 */ int row = k; vector<vector<int>>closest(row, vector<int>(2)); int index = 0; while(heap.size() > 0) { pair<int,int>ptr = heap.top().second; //Added [want to add] the statement to copy elements to closest[][] here closet[index][0] = ptr.first; closet[index][1] = ptr.second; index++; heap.pop(); } Also, I would like to correct your code where you are popping out elements. you should check with the while condition instead of the 'if' condition. The 'if' condition will just pop it once. It is as below: while(heap.size() > k){ heap.pop(); } // if you want to use push_back then you can write as below: // Also correct the code as suggested above with 'if ' condition replaced to 'while' vector<vector<int>>closest(k); int index = 0; while(heap.size() > 0){ pair<int,int>ptr = heap.top().second; closest[index].push_back(ptr.first); closest[index].push_back(ptr.second); index++; heap.pop(); }
70,785,205
70,785,376
Access Derived class (forward declaration) using base class pointer
How to access derived class member variable in my unit test framework(i.e. Gtest_main.cpp) from below scenario. imp.cpp class base{ public: virtual void foo()=0; }; class derived : public base{ public: int abc; // how to access this from Gtest_main.cpp void foo(){ std::cout<<"This is derived foo() \n"; } }; //Unit test framework call on createPlugin to get instance of derived class void createPlugin(base **plugin){ derived *dp = new derived; *plugin=dp; } Gtest_main.cpp (unit test file) class derived //forward declaration base *p; createPlugin(&p); static_cast<derived*>(p)->abc=9090; //error how to access abc? How to access abc in Gtest_main.cpp . Please note i can't modified the original source code impl.cpp
How to access abc in Gtest_main.cpp You can't. Without seeing the full definition of class derived, the compiler has no clue what derived::abc means.
70,785,297
70,998,018
How to make C++ program a Terminal program (UNIX)
I wrote this simple C++ program to compare two strings for a match. Although basic, it's very useful to me as I often need to verify details multiple times a day. I want to initiate the program with a command name e.g. check4match (the program name) so I can run the program in the terminal. #include <iostream> #include <string> using namespace std; void match(string, string); int main() { string addrOne, addrTwo; cout<<"Insert str one: "; cin>>addrOne; cout<<"Insert str two: "; cin>>addrTwo; match(addrOne, addrTwo); return 0; } void match(string addrOne, string addrTwo){ if(addrOne == addrTwo) cout<<"SAFE: strings match"; else cout<<"WARNING: N0 match found"; }
Ok, as always relatively simple in the end. So chmod a+x didn't work to make the cpp program executable. Simple make filename (without the .cpp extension). Then I moved the newly made .exe file to /usr/local/bin. I had to drag & drop the file, as moving via terminal command wasn't allowed, even with sudo.
70,785,390
74,406,914
Code Runner in vsCode ignoring my compiler arguments in my tasks.json file
I am using vsCode with the C/C++ extension and code runner. I want to compile with a -DLOCAL flag so that I can do #ifdef LOCAL ... #endif The problem is that when I compile my code with the code runner extension, it seems to ignore that flag and the #ifdef doesn't work. However, when I use run and debug, the ifdef works. This is my tasks.json, I only added the -DLOCAL flag: { "tasks": [ { "type": "cppbuild", "label": "C/C++: g++.exe build active file", "command": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe", "args": [ "-DLOCAL", "-fdiagnostics-color=always", "-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "group": { "kind": "build", "isDefault": true }, "detail": "Task generated by Debugger." } ], "version": "2.0.0" } When I hit the run button from code runner it runs this command on the command line: cd "d:\vsCodeCompProg\coding5\" ; if ($?) { g++ myfile.cpp -o myfile } ; if ($?) { .\myfile } Here is what is run when I hit run and debug "C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin\g++.exe" -DLOCAL -fdiagnostics-color=always -g D:\vsCodeCompProg\coding5\myfile.cpp -o D:\vsCodeCompProg\coding5\myfile.exe How can I configure code runner so that it follows my tasks.json args? I have looked in the settings for the extension and have not found something that fixes this.
It looks like the code runner is not honoring the tasks.json at all. For me I need to modify the the Code Runner's executorMap by going to: Extensions -> Code Runner -> extension settings -> edit in JSON -> add the -DLOCAL flag in the "cpp" command entry.
70,785,430
70,785,741
How can you catch memory corruption in C++?
I have an std::string which appears to be getting corrupted somehow. Sometimes the string destructor will trigger an access violation, and sometimes printing it via std::cout will produce a crash. If I pad the string in a struct as follows, the back_padding becomes slightly corrupted at a relatively consistant point in my code: struct Test { int front_padding[128] = {0}; std::string my_string; int back_padding[128] = {0}; }; Is there a way to protect the front and back padding arrays so that writing to them will cause a exception or something? Or perhaps some tool which can be used to catch the culprit writing to this memory? Platform: Windows x64 built with MSVC.
In general you have to solve problem of code sanitation, which is quite a broad topic. It sounds like you may have either out-of-bound write, or use of a dangling pointer or even a race condition in using a pointer, but in latter case bug's visibility is affected by obsevation, like the proverbial cat in quantum superposition state. A dirty way to debug source of such rogue write is to create a data breakpont. It is especially effective if bug appears to be deterministic and isn't a "heisenbug". It is possible in MSVS during debug session. In gdb it is possible by using watch breakpoints. You can point at the std::string storage or, in your experimental case, at the front padding array to in attempt to trigger breakpoint where a write operation occurs.
70,785,853
70,786,413
Iterating over pointer array C++
I am new to C++ but I have an experience in C. Now I am trying to iterate over an array of objects but I am getting segmentation fault because it runs out of the range of the array. I have a class ZombieHorede which keeps a pointer to an array of zombies. #pragma once #include "Zombie.hpp" class ZombieHorde { private: static std::string namepool[7]; static std::string typepool[7]; Zombie *zombies; public: ZombieHorde(int N); ~ZombieHorde(void); void announce(void) const; }; The constructor of this class takes a number N and initializes the array of N zombies. Like this. ZombieHorde::ZombieHorde(int N) { int i; i = 0; this->zombies = new Zombie[N]; while (i < N) { this->zombies[i].set_name(this->namepool[rand() % 7]); this->zombies[i].set_type(this->typepool[rand() % 7]); i++; } } Now I want to iterate over zombies and call a function on each of them ... like this... void ZombieHorde::announce() const { int i; i = 0; while (&this->zombies[i]) { this->zombies[i].announce(); i++; } } And the announce function gives segmentation fault cuz i goes beyond the range of the array with this main: #include "ZombieHorde.hpp" int main() { ZombieHorde horde(4); horde.announce(); } Now the main question is how to iterate over the zombies array in order to not get a segmentation fault. ATTENTION: Note that this is a 42 school exercise and I am not allowed to use STL of C++. I should allocate zombies at once in the constructor.
question is how to iterate over the zombies array in order to not get a segmentation fault. One way to resolve this would be to have a data member called zombieSize that stores the value of N as shown below in the modified snippets: class ZombieHorde { private: static std::string namepool[7]; static std::string typepool[7]; Zombie *zombies; std::size_t zombieSize; //data member that is used to store the value of N public: ZombieHorde(int N); ~ZombieHorde(void); void announce(void) const; }; //use member initializer list to initialize zombieSize ZombieHorde::ZombieHorde(int N): zombieSize(N) { int i; i = 0; this->zombies = new Zombie[zombieSize];//use data member zombieSize instead of N while (i < zombieSize)//use zombieSize instead of N { this->zombies[i].set_name(this->namepool[rand() % 7]); this->zombies[i].set_type(this->typepool[rand() % 7]); i++; } } void ZombieHorde::announce() const { int i; i = 0; while (i < zombieSize)//use zombieSize instead of N { this->zombies[i].announce(); i++; } }
70,785,866
70,786,578
C++ coroutine's return_void's and return_value's return type
return_void consider the coroutine's ReturnObject below and note the comments before the method ReturnObject::promise_type::return_void : struct ReturnObject { struct promise_type { int val_{23}; ReturnObject get_return_object() { return {std::coroutine_handle<promise_type>::from_promise(*this)}; } std::suspend_never initial_suspend() { return {}; } std::suspend_never final_suspend() noexcept { return {}; } void unhandled_exception() {} /*** NOTE THIS ***/ //void return_void(){ } /*** AND THIS ***/ int return_void(){ return 101; } }; std::coroutine_handle<promise_type> h_; ReturnObject(std::coroutine_handle<promise_type> h):h_{h}{ } operator std::coroutine_handle<promise_type>() const { return h_; } }; Full code on compiler explorer The standard usage on the web and in this paper (page 37) suggests that the return_void method returns void but in gcc 11.2, the return_void with int return type works as well. Is this correct ? If yes, why does it work with both void and non-void return type ? what happens to the return value of the return_void in the case of non-void return type? return_value Similar effects with the method return_value can be observed in gcc. In case of the return_value's returned data, is there a way to access this returned data directly, similar to the normal subroutine/function's returned value ? Check the code on compiler explorer Update: After @useless's suggestion, I added [[nodiscard]] to both return_void and return_value with non-void return types and enabled -Wall flag. Surprisingly for return_void and return_value I don't even get a warning with gcc-10.2. Check here but gcc-11.2 gives me a warning (here) The compiler warning I get for return_value with int return type looks like below warning: ignoring return value of 'int ReturnObject::promise_type::return_value(int)', declared with attribute 'nodiscard' [-Wunused-result] 31 | co_return 7; | ^ <source>:18:27: note: declared here 18 | [[nodiscard]] int return_value(int val){return val;} I'm not convinced from the compiler warning that co_returns value is being discarded. In reality the return value being discarded is from the method return_value but the compiler manages to shroud it some how. Thanks for looking at the post and for suggestions in advance.
[stmt.return.coroutine]/2 says that the expressions promise_object.return_value(...) and promise_object.return_void() (whichever is used by the co_return) shall be of type void. So the return type of either function must be void (if it is used by a co_return). MSVC does correctly reject the program: <source>(31): error C7625: The type of a coroutine promise return_value or return_void expression must be void <source>(18): note: see declaration of 'ReturnObject::promise_type::return_value'