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,813,025
70,814,207
Argmax of 2d vector on C++
I am working on python/pytorch and I have an example like 2d vector a | v dim-0 ---> -----> dim-1 ------> -----> --------> dim-1 | [[-1.7739, 0.8073, 0.0472, -0.4084], v [ 0.6378, 0.6575, -1.2970, -0.0625], | [ 1.7970, -1.3463, 0.9011, -0.8704], v [ 1.5639, 0.7123, 0.0385, 1.8410]] | v Then, the argmax with the index of 1 will be # argmax (indices where max values are present) along dimension-1 In [215]: torch.argmax(a, dim=1) Out[215]: tensor([1, 1, 0, 3]) My question is that given the 2d vector a as above, how could I implement argmax function on C++ to give me same output as above? Thanks for reading This is what I did vector<vector<float>> a_vect { {-1.7739, 0.8073, 0.0472, -0.4084}, {0.6378, 0.6575, -1.2970, -0.0625}, {1.7970, -1.3463, 0.9011, -0.8704}, {1.5639, 0.7123, 0.0385, 1.8410} }; std::vector<int>::iterator max = max_element(a_vect.begin() , a_vect.end()-a_vect.begin());
You can use std::max_element to find the index in each sub vector #include <algorithm> #include <iostream> #include <vector> using std::vector; int main() { vector<vector<float>> a_vect= { {-1.7739, 0.8073, 0.0472, -0.4084}, {0.6378, 0.6575, -1.2970, -0.0625}, {1.7970, -1.3463, 0.9011, -0.8704}, {1.5639, 0.7123, 0.0385, 1.8410} }; vector<int> max_index; for(auto& v:a_vect) max_index.push_back(std::max_element(v.begin(),v.end())-v.begin()); for(auto i:max_index) std::cout << i << ' '; // 1 1 0 3 }
70,813,613
70,813,787
"Invalid base class" error when trying to inherit from derived struct (C++)
I've got a "Base" struct, an "NPC" struct derived from the "Base". All works perfectly fine. But when I try to create a new struct called "PC" from the "NPC" struct, I get an error: "invalid base class". What's the problem? Is it not possible to create a struct from a derived struct? struct Base { char* name = 0; int MaxHP = 0; int CurrHP = 0; }; struct NPC : Base { int gold = 0; int stats[]; }; struct PC : NPC // I get the error here { unsigned int ID = 0; };
When you wrote: struct NPC : Base { int gold = 0; int stats[]; //NOT VALID, this is a definition and size must be known }; This is not valid as from cppreference: Any of the following contexts requires type T to be complete: declaration of a non-static class data member of type T; But the type of the non-static data member stats is incomplete and hence the error.
70,813,733
70,814,064
Error: " expected unqualified-id before 'int' ", array, argument, function,
I am fairly new to C++ and currently following a certification to learn this language. I previously only used languages such as Python. I found similar posts with the same but none could relate to my code. I have the following code to create a hex game. I am trying to have a simple function to display the board every time a player makes a moove. I try to keep the code as simple as possible at first (limit the use of pointers and libraries). I have this error : hex_game.cpp:9:47: error: expected unqualified-id before 'int' 9 | void display_current_array(array[size][size], int size){ | Below is my code, hope someone could help : #include <iostream> #include <stdlib.h> using namespace std; #include <vector> #include <array> // a void function to display the array after every moove void display_current_array(array[size][size], int size){ //s=arr.size(); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { cout<<array[i][j]<<endl; } } } int main(){ // the HEX game is a game of size cases represented by an array either filled with a color; // int size =11; //as asked but we can play on a differnt board int size; // ask the player to give a board size cout << "What is the size of your Hex Board ? "; cin>> size; // create the array to represent the board int array[size][size]; // the player will choose colors that we will store as an enum type enum colors {BLUE, RED}; // initialize the array: all positions are 0 for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { array[i][j]=0; } } display_current_array(array, size); }
In Standard C++ the size of an array must be a compile time constant. So when you wrote: int size; cin>> size; int array[size][size]; //NOT STANDARD C++ The statement array[size][size]; is not standard c++. Second when you wrote: void display_current_array(array[size][size], int size){ //... } Note in the first parameter of the function display_current_array you have not specified the type of elements that the array holds. So this will result in the error you're getting. Solution A better way to avoid these complications is to use a dynamically sized container like std::vector as shown below: #include <iostream> #include <vector> // a void function to display the vector after every moove void display_current_array(const std::vector<std::vector<int>> &vec){//note the vector is passed by reference to avoid copying for(auto &row: vec) { for(auto &col: row) { std::cout << col ; } std::cout<<std::endl; } } int main(){ int size; // ask the player to give a board size std::cout << "What is the size of your Hex Board ? "; std::cin>> size; // create the 2D STD::VECTOR with size rows and size columns to represent the board std::vector<std::vector<int>> vec(size, std::vector<int>(size)); // the player will choose colors that we will store as an enum type enum colors {BLUE, RED}; //NO NEED TO INITIALIZE EACH INDIVIDUAL CELL IN THE 2D VECTOR SINCE THEY ARE ALREADY INITIALIED TO 0 display_current_array(vec); } Note that: We don't need to pass size of the vector as an argument the vector is passed by reference to avoid copying The output of the above program can be seen here.
70,813,892
70,816,684
custom exception class, using a base class, with multiple arguments
So I'm setting up custom exception classes for a program I am writing. I'm creating a catch-all base class, that I will use primarily as a generic exception. This base class will be inherited by several other custom exceptions. Here is the base class and one of the additional exception classes, there will be 10+ child classes that inherit from the parent class. #include <exception> #include <string> #include <string.h> class AgentException : public std::exception { protected: char *msg; public: AgentException() : msg("AgentException"){}; AgentException(char *m) : msg(m){}; AgentException(char *m, std::string d) { strcat(m, d.c_str()); //aware this fails. its a segmentation fault }; ~AgentException() = default; const char *what() const throw() { return (const char *)msg; } }; class ConnectionFailed : public AgentException { private: std::string eType = "ConnectionFailed"; public: ConnectionFailed() : AgentException("ConnectionFailed"){}; ConnectionFailed(std::string d) : AgentException("ConnectionFailed: ", d){}; ~ConnectionFailed() = default; }; I'm aware with the above code that what() will not currently return anything as the member variable is not being assigned. I left that out, because I'm getting a segmentation fault from the strcat() call. I've created multiple constructors for the parent class, as there will be times that I want the default value, a single value, or even two arguments passed. In the case of the child class, it will always be passing at least the class ID to the parent, where in some cases I may need to pass a string variable along with the class id. The string variable, std::string, is a must. Those were the directives I was given to use. Originally I set up all message variables as std::string within the classes, but I ultimately ran into a problem related to the what() function. I couldn't figure out how to convert the std::string to return as a const char*. After doing some research, I found out that it was a bad idea to utilize strings within an exception class, as what's going to catch any exceptions that may occur within So I converted everything back to const char*, but now I can't seem to get a return from what(). The problems all stem from my inability to figure out the concatenation of the different types. I can get something working passably with this change to the AgentException class. protected: char msg[100]; public: // AgentException() : msg("AgentException"){}; // AgentException(char *m) : msg(m){}; AgentException(const char *m, std::string d) { strcpy(msg, m); strcat(msg, d.c_str()); }; I can make this change work overall, but it doesn't feel like it's the correct way of doing this. Could someone provide me some insight into the changes they would make to this setup? I'm currently testing by throwing either the AgentException or ConnectionFailed exception and catching with the Base AgentException. I've been rotating to see if there are any different reactions. try { throw ConnectionFailed("test"); } catch (const AgentException &e) { std::cout << "----------------" << std::endl; std::cerr << e.what() << '\n'; std::cout << "_________________" << std::endl; }
As Silvio mentioned in another comment, you can't use strcat if the buffer can't contain the resulting string. In this case, you also have the problem that you're passing a const char * to strcat which is a no no (literal strings are const). I suggest that you change your msg variable to a std::string. It will then be able to grow to accommodate the concatenated message, and manage the memory for you. class AgentException : public std::exception { protected: std::string msg; public: AgentException() : msg("AgentException") {}; AgentException(const char *m) : msg(m){}; AgentException(const char *m, const std::string& d) { msg = m + d; }; ~AgentException() = default; const char *what() const throw() { return msg.c_str(); } }; class ConnectionFailed : public AgentException { public: ConnectionFailed() : AgentException("ConnectionFailed"){}; ConnectionFailed(const std::string& d) : AgentException("ConnectionFailed: ", d){}; ~ConnectionFailed() = default; };
70,814,312
70,816,325
Mouse click with GetAsyncStateKey
I am trying to make a program that when you click, it uses GetAsyncStateKey() to know that you've clicked and makes the code click once more, like a double-clicker. The problem is, I don't know anything about coding, so I tried to look at many codes and came up with this: #include <iostream> #include <windows.h> #include <fstream> using namespace std; int main() { if(GetAsyncKeyState(VK_LBUTTON)) { mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); Sleep(0); return 0; } } In my mind, when it opens, it should stay open, hence the sleep, then getting the part if I click, it clicks again. But in reality, when I open it, it closes immediately. Can someone make it work for me?
Your program performs 1 operation and then exits. You need a loop to keep it alive, eg: #include <iostream> #include <windows.h> using namespace std; int main() { while (true) { if (GetAsyncKeyState(VK_LBUTTON) < 0) { mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0); } Sleep(0); } return 0; }
70,814,930
70,814,998
How to implement arrays of abstract classes in C++?
My use case is the following. I have a pure abstract class and inherited classes like so: class AbstractCell { public: // data members virtual void fn () = 0; // pure virtual functions } class DerivedCell1 : public AbstractCell { public: // more data members void fn () {} // implementation of all virtual functions } class DerivedCell2 : public AbstractCell { public: // more data members void fn () {} // implementation of all virtual functions } Now, I want to create an array of the abstract class as a member of another class. class AbstractGrid { public: AbstractCell m_cells [10][10]; // this is illegal void printCells() { // accesses and prints m_cells // only uses members of AbstractCell } } class DerivedGrid1 : public AbstractCell { public: DerivedCell1 m_cells [10][10]; // I want this class to use DerivedCell1 instead of AbstractCell } class DerivedGrid2 : public AbstractCell { public: DerivedCell2 m_cells [10][10]; // I want this class to use DerivedCell2 instead of AbstractCell } How should I go about achieving this? Constraints: For runtime efficiency, I want to use fixed-size arrays and not dynamic memory allocation (new or smart pointers). I want a solution other than using template classes. I'm currently using templates, but I'm wondering if there's a better way.
Abstract classes rely on virtual functions to be useful. The right function to be called is determined at runtime depending on the real type of the polymorphic object. You cannot benefit of such polymorphism with an array of objects. Arrays require a type that is determined at compile-time and that can be instantiated. This is incompatible with abstract classes. If you want an array with abstract classes, you have to go for an array of pointers. And typically, you'd use unique_ptr or shared_ptr, to avoid accidents in memory management. You can use new/delete if you prefer, but at your own risk. If you love templates and are worried about performance of dynamic memory allocation, you may have a look at Alexandrescu's Modern C++ design.
70,814,941
70,815,042
memory address of dynamic array
double *tt; tt = new double[2]; std::cout << tt[0] << std::endl; std::cout << tt << std::endl; The result is like this -1.72723e-77 0x12e6062e0 What is the difference between these two? I don't know why the two values ​​have different formats (tt[0] is X.~~ but tt there is no point)
tt[0] is dereferencing the pointer to the array tt and the result is an expression of type double. It is equivalent to *tt. There is a random value in that location so you see a random floating-point value being printed. But tt is just a pointer (of type double*) and thus when you print it, the address of a memory location (the address of the first byte of the array) is displayed. C-style arrays automatically decay into a pointer.
70,814,975
70,815,305
How can I draw an ellipse using QPainter?
I want to draw ellipse in UI but my code doesn't work. QWidget::paintEngine: Should no longer be called QPainter::begin: Paint device returned engine == 0, type: 1 Mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow), pm(100,100) { ui->setupUi(this); //set_form_style(); draw_ellipse(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::set_form_style(){ //setWindowFlags(Qt::FramelessWindowHint); //setAttribute(Qt::WA_TranslucentBackground); //ui->widget->setStyleSheet("background:transparent;"); setMouseTracking(true); } void MainWindow::draw_ellipse(){ QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.setBrush(QBrush(Qt::red, Qt::SolidPattern)); painter.drawEllipse(100, 50, 150, 150); }
The issue isn't the way you're using the QPainter, it's the time you're obtaining it. As the reference documentation says, "the common use of QPainter is inside a widget's paint event". So if you want to do custom painting in your main window, override paintEvent and put your code there.
70,815,062
70,815,229
Calling destructor in member function
If we are implementing, for example, smart pointers, and we want to do a = std::move(b) --- we need to delete memory to which a is pointing, but can we call destructor inside move assignment operator, instead of copy-pasting destructor's function body? Is the behavior on calling destructor inside move-assignment defined? If it's not, are there any better ways dealing with it rather than copy-pasting destructor's body?
Explictly calling destuctor is technically available, you can use this->~Object() in non static method of the class Object. However this is a bad practice. Consider use these instead. class Test { public: Test() {} ~Test() { Deallocate(); } Test(const Test& other) = delete; Test(Test&& other) { Deallocate(); // Do sth } private: void Deallocate() { // Do sth } };
70,815,347
70,815,452
How can I delete decimal points from a 'double' type to later be displayed as a currency?
I am currently building a mock banking app that can display the history of transactions on an account. Part of a transaction is, naturally, the amount. Amounts are stored as doubles in my program which leads to many of them being displayed with way too many decimal points (for example £500.000000 instead of £500.00). When forming a transaction, the amount is simply converted to a string alongside timestamps and transaction types. I need a way so that the double can be stored without the extra decimal places. It doesn't matter if it is converted to two decimal places before or after becoming a string. I cannot use setprecision(2) here because I am not writing out the transaction to the console yet. Transaction::Transaction(string desc, string timestamp, double value) { this->desc = desc; this->timestamp = timestamp; this->value = value; }; string Transaction::toString() { fullString = "-- " + desc + ": -\x9c" + to_string(value) + " on " + timestamp; }
You may use this helper function: #include <sstream> #include <iomanip> std::string value2string(double value) { std::ostringstream out; out << std::fixed << std::setprecision(2) << value; return out.str(); } string Transaction::toString() { fullString = "-- " + desc + ": -\x9c" + value2string(value) + " on " + timestamp; }
70,815,729
70,816,426
How do we handle errors in the input of a User Defined Literal?
Say I want to have an integral percent defined like so: constexpr int operator""_percent (char const * literal) { int percent(0); for(; *literal != '\0'; ++literal) { if(*literal >= '0' && *literal <= '9') { percent *= 10; percent += *literal - '0'; if(percent > 100) { ...what do we do here?... } } else { ...what do we do here?... } } return percent; } I was thinking of throwing, but I remember that a constexpr and throw do not match well (or is that only in C++14 and older?). What is the convention in that situation? What is the correct way to report an error in a User Defined Literal operator? Note: I'm currently on C++17 but plans to soon switch to C++20.
I don't really know what common practice for such situations is, but I will give some ideas below. With C++20 you can make the literal operator consteval instead of constexpr. On error you can then throw an exception. The throw expression itself is allowed in a constexpr/consteval function, but actually throwing makes it not a constant subexpression. Since consteval function invocations must be constant expressions, the program will then be ill-formed on error and the compiler must diagnose it. For C++17 you can still throw an exception, but consteval is not available. For valid literals this is not a problem. As long as the throw expression wouldn't be evaluated, the call to the literal operator can still be a constant subexpression. If however the literal is invalid, you will generally not get a compile-time diagnostic if it isn't used in a context requiring a constant expression. Instead you will get an exception thrown during program execution when the literal is evaluated. This might be undesirable, for example if the literal is supposed to be used in a noexcept function. Alternatively you could also use assert instead of throwing exceptions. Since C++17 it is guaranteed to be a constant subexpression if the argument evaluates to true. If the assertion fails, you will not get a compile-time error either, instead the program will abort when the literal is evaluated. Using the NDEBUG macro the assertion can be removed in release builds. This doesn't affect the exception specification, but you will still need to decide on how to handle errors in the release build which weren't caught in debug build testing. This might not be safe enough for your use. I don't think there is any C++17 way of forcing a compile-time error in general. As I mentioned in the comments to the question, I have some doubts that my suggestions are correct/good. So read them as well, please.
70,815,794
70,816,026
How to display a map of a map (C++)?
I made the following map to store data from a .log : map<string,pair(int,map<string,int>)>. I manage to store the data but not to retrieve it. What I do is: cout<< "first string: "<< debut->first << " pair (first int): " << debut->second.first << endl; (debut is a constant iterator of a map) With that I get the first string and the int of the pair, but I don't know how to get the content of the map. I tried different syntaxes as debut->second.second->first or debut->second.second.first but of them work. Does someone have an idea?
I don't know how to get the content of the map. You can print out the content of the innermost map as shown below([DEMO]): auto beg = debut->second.second.cbegin(); auto end = debut->second.second.cend(); while(beg!=end) //can also use for loop { std::cout<<beg->first<<" "; std::cout<<beg->second<<std::endl; ++beg; } Here is a more complete example for printing the all the content of the maps, just for demonstration: #include <iostream> #include <map> int main() { std::map<std::string,std::pair<int,std::map<std::string,int>>> m{ { "first", { 5, {{"a", 10}, {"b", 20}} }} , { "second", { 6, {{"c", 100}, {"d", 200},{"e", 300} }}}, { "third", { 7, {{"f", 400}} } }}; ////////////////////////////////////////////////////////////////// //PRINTING THE CONTENT OF THE MAP auto debutBegin = m.cbegin(); //const iterator to beginning of outer map auto debutEnd = m.cend(); //const iterator to end of outer map while(debutBegin!=debutEnd) { auto beg = debutBegin->second.second.cbegin(); //const iterator to beginning of inner map auto end = debutBegin->second.second.cend();//const iterator to end of inner map std::cout<<debutBegin->first<<" ---- "<<debutBegin->second.first<<std::endl; while(beg!=end) { std::cout<<beg->first<<" "; std::cout<<beg->second<<std::endl; ++beg; } debutBegin++; } return 0; } Output The output of the above program is: first ---- 5 a 10 b 20 second ---- 6 c 100 d 200 e 300 third ---- 7 f 400
70,816,188
70,816,471
How to create a vector of unique pointers pointing at default constructed objects
Is there a way to create a vector containing N number of std::unique_ptr<T>s? GCC v11.2 shows huge and cryptic error messages so I'm not able to detect the issue. Here is an MRE of what I was trying to do: #include <iostream> #include <vector> #include <memory> // a dummy struct struct Foo { int m_value; }; int main( ) { constexpr auto rowCount { 10uz }; constexpr auto colCount { 20uz }; // a 1D vector of pointers, does not compile std::vector< std::unique_ptr<Foo> > vec_1D( colCount, std::make_unique<Foo>( ) ); for ( const auto& ptr : vec_1D ) { std::cout << "Address: " << ptr << " --- value: " << ptr->m_value << '\n'; } // a 2D vector of pointers, does not compile std::vector< std::vector< std::unique_ptr<Foo> > > matrix( rowCount, std::vector< std::unique_ptr<Foo> >( colCount, std::make_unique<Foo>( ) ) ); } I think I'm missing something important about std::unique_ptr here. Is this error because of the fact that unique_ptr is not copy-constructible? If the above method is not possible, then what could be the alternative?
The line: std::vector< std::unique_ptr<Foo> > vec_1D( colCount, std::make_unique<Foo>( ) ); makes use of the following vector constructor: vector( size_type count, const T& value, const Allocator& alloc = Allocator()); Which receives a given value and copies it to every element of the vector. From cppreference: Constructs the container with count copies of elements with value value. So you are calling std::make_unique<Foo>(), getting a std::unique_ptr<Foo>&& back from that call, and passing it to the std::vector's constructor so that it copies it across. The problem is that that unique pointer is not copyable. You could though: create a vector with a given size, and for every element in the vector, create a unique pointer (one at a time), and move assign that unique pointer to the vector's element. The example below uses std::generate to fill the vector. Notice that the generator function is returning a std::unique_ptr<Foo>&& that is move assignable to each vector's element. [Demo] #include <algorithm> // generate #include <iostream> // cout #include <memory> #include <vector> // a dummy struct struct Foo { Foo() : m_value{value++} {} static inline int value{}; int m_value{}; }; int main( ) { const size_t count{ 20 }; std::vector<std::unique_ptr<Foo>> v(count); std::generate(v.begin(), v.end(), []() { return std::make_unique<Foo>(); }); for (auto&& up : v) { std::cout << up->m_value << " "; } } // Outputs // // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
70,816,425
70,817,236
Declaring a std::list with an array index C++
I was following a hash table implementation online (https://www.youtube.com/watch?v=2_3fR-k-LzI) when I observed the video author initialize a std::list with an array index. This was very confusing to me as I was always under the impression that std::list was always meant to operate like a linked list and was not capable of supporting random indexing. However, I thought it was maybe a weird way to declare the size of a list and ignored it and moved on. Specifically, he did the following: static const int hashGroups = 10; std::list<std::pair<int, std::string>> table[hashGroups]; Upon trying to implement a function to search to see if a key resided in the hash table, I realized that I could not access the std::list objects as I would expect to be able to. In HashTable.cpp (which includes the header file that defines the two variables above) I was only able to access the table member variable's elements as a pointer with -> instead of with . as I would expect to be able to. It looks like what is directly causing this is using the array index in the list definition. This seems to change the type of the table variable from a std::list to a pointer to a std::list. I do not understand why this is the case. This also appears to break my current implementation of attempting to iterate through the table variable because when I declare an iterator to iterate through table's elements, I am able to see that the table has the correct data in the VS debugger but the iterator seems to have completely invalid data and does not iterate through the loop even once despite seeing table correctly have 10 elements. My attempt at the search function is pasted below: std::string HashTable::searchTable(int key) { for (std::list<std::pair<int, std::string>>::const_iterator it = table->begin(); it != table->end(); it++) { if (key == it->first) { return it->second; } std::cout << "One iteration performed." << std::endl; } return "No value found for that key."; } With all of this being said, I have several burning questions: Why are we even able to declare a list with brackets when a std::list does not support random access? Why does declaring a list like this change the type of the list from std::list to a pointer? What would be the correct way to iterate through table in its current implementation with an iterator? Thank you for any help or insight provided!
After reading the responses from @IgorTandetnik I realized that I was thinking about the list incorrectly. What I didn't fully understand was that we were declaring an array of lists and not attempting to initialize a list like an array. Once I realized this, I was able to access the elements correctly since I was not trying to iterate through an array with an iterator for a list. My revised searchTable function which to my knowledge now works correctly looks like this: std::string HashTable::searchTable(int key) { int hashedKey = hashFunction(key); if (table[hashedKey].size() > 0) { for (std::list<std::pair<int, std::string>>::const_iterator it = table[hashedKey].begin(); it != table[hashedKey].end(); it++) { if (key == it->first) { return it->second; } } } return "No value found for that key."; } And to answer my three previous questions... 1. Why are we even able to declare a list with brackets when a std::list does not support random access? Response: We are declaring an array of std::list that contains a std::pair of int and std::string, not a list with the array index operator. 2. Why does declaring a list like this change the type of the list from std::list to a pointer? Response: Because we are declaring table to be an array (which is equivalent to a const pointer to the first element) which contains instances of std::list. So we are never "changing" the type of the list variable. 3. What would be the correct way to iterate through table in its current implementation with an iterator? Response: The current implementation only attempts to iterate over the first element of table. Create an iterator which uses the hashed key value as the array index of table and then tries to iterate through the std::list that holds instances of std::pair at that index.
70,816,674
70,817,550
Passing a member function as template argument
I have a hash table class. It has a template parameter hashFunction: #include <string> template<class KeyType> using hashFunction_t = size_t(size_t, const KeyType&); template< class KeyType, class ValueType, int nHashGroups, hashFunction_t<KeyType> hashFunction > class HashTable { }; class Entity { //djb2 size_t stringHash(size_t nGroups, const std::string& key) { unsigned long hash = 5381; const char* str = key.c_str(); int c = 0; while (c = *str++) hash = ((hash << 5) + hash) + c; return hash % nGroups; } HashTable <std::string, int, 10, stringHash> ht; }; int main() { Entity{}; } I would prefer to hide stringHash function inside the Entity class as a private function but doing that gives me an error: Error (active) E0458 argument of type "size_t (Entity::*)(size_t nGroups, const std::string &key)" is incompatible with template parameter of type "hashFunction_t<std::string> *" How can I do this?
The problem is that you are trying to use a pointer-to-member as a type template parameter, and this is not supported, basically because when you define a type you don't bind that type to any specific object. When (as suggested in a comment) you make stringHash static, then you no longer need the object, so it can be used to define the type. If you still need to have stringHash from a non-static member, then you can change the template to something like the below. Be aware that you have to pass the object to the HashTable in order to call the hashFunction. Also, keep an eye on the syntax to call it. template<class KeyType, class Obj> using hashFunction_t = size_t(Obj::*)(size_t, const KeyType&); template< class KeyType, class ValueType, int nHashGroups, class Obj, hashFunction_t<KeyType, Obj> hashFunction> class HashTable { public: explicit HashTable(Obj& obj) : m_obj{obj} { (m_obj.*hashFunction)(10, ""); // arguments just for illustrative purposes } private: Obj& m_obj; // keep a reference to the object to call the method // be careful with dangling references }; class Entity { size_t stringHash(size_t nGroups, const std::string& key) /* ... */ // Pass a reference to the object HashTable <std::string, int, 10, Entity, &Entity::stringHash> ht{*this}; };
70,816,714
70,816,794
Why my program isn't accepting the second input?
I don't know why it doesn't take the second input. Help me solve it. This is the code: #include <iostream> using namespace std; int main() { char fn,ln; cout<<"Enter your First Name\n"<<endl; cin>>fn; cout<<"Enter your Last Name"<<endl; cin>>ln; return 0; }
Since char can only hold a single character, you may use std::string for storing names. Example: #include <iostream> #include <string> int main( ) { std::cout << "Enter your first name\n"; std::string firstName; std::getline( std::cin, firstName ); std::cout << "Enter your last name\n"; std::string lastName; std::getline( std::cin, lastName ); std::cout << "\nHi " << firstName << ' ' << lastName << '\n'; } Sample input/output: Enter your first name John Enter your last name Connor Hi John Connor
70,816,850
70,816,894
How Does Vertex Buffer Description Read Input Data in DirectX 11?
I created a Math Struct that holds positions for vertex coordinates and am wondering how DirectX is able to read the members of the struct without knowing the names of the member values or being able to use them for input despite them being private. Example: //The values can be used for input despite being private class Math3 { public: Math3() {} Math3(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {} private: float x; float y; float z; };
The private vs public only applies to C++ code and is enforced by the compiler. Instances of Math3 are just a block of 12 bytes in memory with no special hardware protections. In other words, from an 'in-memory' perspective the Math3 is exactly the same if it's: class Math3 { public: float x; float y; float z; }; // this is the same as struct Math3 { float x; float y; float z; } If you do a sizeof on the class, it's the same. A vertex buffer is just a block of memory. The GPU knows the data type, size, padding, etc. from the Input Layout description when you create the input layout. const D3D11_INPUT_ELEMENT_DESC InputElements[] = { { "SV_Position", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; If you added a virtual method to your Math3 class, then the layout of the memory would change and it would no longer 'just work'. The Input Assembler takes the active Input Layout and uses it to parse the vertex information out of one or more vertex buffers. Therefore, it's able to understand a variety of complex layouts and even merge from multiple buffers at runtime. In the end, all that matters is that your C++ code uses the same 'in-memory' organization for vertex data as described by the input layout and that your Vertex Buffer itself respects that organization.
70,816,917
70,817,015
Perfect forwarding of a braced initializer to a constructor?
There are similar questions, but none seem to be quite this. I have a wrapper class that exists to hold an S. In it's simplest form we have // A simple class with a two-argument constructor: struct S { int x[2]; S(int x, int y) : x{x, y} {} }; struct WrappedSSimple { S s; template <typename... Args> WrappedSSimple(Args&&... args) : s(std::forward<Args>(args)...) {} }; which seems to work when I call WrappedSSimple({1,2}). However, I want to make the c'tor private and have a static factory function. That fails: struct WrappedS { S s; template <typename... Args> static WrappedS make(Args&&... args) { return WrappedS(std::forward<Args>(args)...); } private: template <typename... Args> WrappedS(Args&&... args) : s(std::forward<Args>(args)...) {} }; with <source>:28:14: error: no matching function for call to 'make' auto w = WrappedS::make({1,2}); // This is not. ^~~~~~~~~~~~~~ <source>:19:21: note: candidate template ignored: substitution failure: deduced incomplete pack <(no value)> for template parameter 'Args' static WrappedS make(Args&&... args) { return WrappedS(std::forward<Args>(args)...); } ^ https://godbolt.org/z/rsWK94Thq Is there a way to perfectly forward the braces through the static make function?
In your first example WrappedSSimple({1,2}) is calling the move-constructor of WrappedSSimple with the a temporary constructed via the user-defined constructor as argument. You cannot replicate this behavior with a factory if the constructor is private, because the temporary object which needs access to the constructor is always created in the context of the caller. You can also not generally forward untyped braces. The best you can do, if you are fine with restricting the types to be the same for each element of the brace, is to use a std::initializer_list or a reference to an array as parameter to make.
70,817,174
70,817,195
How can I read a single byte from a binary stream?
I have a binary file which I would like to process one byte at a time. This is what I have for reading the first character of the file: ifstream file("input.dat", ios::binary); unsigned char c; file >> c; However, when I step through this code with a debugger, c always has the value 0x00 although the first (and only) character of the file is 0x0A. In fact, any other character is also totally ignored. How do I read individual bytes from this file?
Use std::istream::get or std::istream::read. char c; if (!file.get(c)) { error } int c = file.get(); if (c == EOF) { error } char c; if (!file.read(&c, 1)) { error } And finally: unsigned char c; if (!file.read(reinterpret_cast<char*>(&c), 1)) { error }
70,817,312
70,817,334
Adding char[] to vector
Trying to add value to vector : std::vector<char[256] > readers; char d[256]; strcpy(d, "AAA"); readers.push_back(d); Got error: an array cannot be initialized with a parenthesized initializer What I do wrong?
A C-style array is not assignable, so it cannot be used as the value type of a vector. If you are using at least C++11, you can #include <array> and use std::array. (Historically available in Visual C++ 2008 SP1 as std::tr1::array). #include <iostream> #include <array> #include <vector> #include <cstring> int main() { std::vector< std::array<char, 256>> readers; std::array<char,256> d; strcpy(d.data(), "AAA"); readers.push_back(d); }
70,817,628
70,817,686
Create std::string from std::span of unsigned char
I am using a C library which uses various fixed-sized unsigned char arrays with no null terminator as strings. I've been converting them to std::string using the following function: auto uchar_to_stdstring(const unsigned char* input_array, int width) -> std::string { std::string temp_string(reinterpret_cast<const char*>(input_array), width); temp_string.erase(temp_string.find_last_not_of(' ') + 1); return temp_string; } Which works fine, other than the use of reinterpret_cast, the need to pass the array size and the fact that I'm decaying an array into a pointer. I'm trying to avoid all of these issues with the use of std::span. The function that uses std::span looks like this: auto ucharspan_to_stdstring(const std::span<unsigned char>& input_array) -> std::string { std::stringstream temp_ss; for (const auto& input_arr_char : input_array) { temp_ss << input_arr_char; } return temp_ss.str(); } The function works well, makes everything else simpler without having to track the C array's size. But, a little further digging with some benchmarking (using nanobench) shows that the new function is many times slower than the classic reinterpret_cast method. My assumption is that the for loop in the std::span-based function is the inefficiency here. My question: Is there a more efficient method to convert a fixed-size C array of unsigned chars from a std::span variable to a std::string? Edit: gcc benchmark (-O3 -DNDEBUG -std=gnu++20, nanobench, minEpochIterations=54552558, warmup=100, doNotOptimizeAway) relative ns/op op/s err% ins/op bra/op miss% total uchar[] to std::string 100.0% 5.39 185,410,438.12 0.3% 80.00 20.00 0.0% 3.56 uchar 2.1% 253.06 3,951,678.30 0.6% 4,445.00 768.00 0.0% 167.74 ucharspan 1,244.0% 0.43 2,306,562,499.69 0.2% 9.00 1.00 0.0% 0.29 ucharspan_barry 72.8% 7.41 134,914,127.56 1.3% 99.00 22.00 0.0% 4.89 uchar_bsv clang benchmark (-O3 -DNDEBUG -std=gnu++20, nanobench, minEpochIterations=54552558, warmup=100, doNotOptimizeAway) relative ns/op op/s err% ins/op bra/op miss% total uchar[] to std::string 100.0% 2.13 468,495,014.11 0.2% 14.00 1.00 0.0% 1.42 uchar 0.8% 251.74 3,972,418.54 0.2% 4,477.00 767.00 0.0% 166.30 ucharspan 144.4% 1.48 676,329,668.07 0.1% 7.00 0.00 95.8% 0.98 ucharspan_barry 34.5% 6.19 161,592,563.70 0.1% 80.00 24.00 0.0% 4.08 uchar_bsv (uchar_bsv in the benchmarks is the same as ucharspan_barry, but with a std::basic_string_view<unsigned char const> parameter instead of std::span<unsigned char const>
You want: auto ucharspan_to_stdstring(std::span<unsigned char const> input_array) -> std::string { return std::string(input_array.begin(), input_array.end()); } string, like other stand library containers, is constructible from an appropriate iterator pair - and this is such a pair. Since these are random access iterators, this will do a single allocation, etc. Note that I changed from span<T> const& to span<T const>, for two reasons. First, you're not mutating the contents of the span, so the inner type needs to be const... similar to how you took a T const*, not a T*. Second, you should take spans by value because they're cheap to copy (unless you very specifically need the identity of the span, which you don't here). It may be better to do a reinterpret_cast so that you can use the (char const*, size_t) constructor - this one ensures a single memcpy for the eventual write. But you'd have to time it to see if it's worthwhile.
70,817,998
70,818,055
Why does this while loop keep looping even when its false? In C++
This is the code in question: int integer; while (integer != 0 || integer != 1) { cout << "Choose an integer: \n0\n1\n"; cin >> integer; } When I type 1 it continues looping even though the statement is false. I have had this problem before or similar but it got fixed in a weird way that seems to not be working right now. The other code that was having problems was this one: while(chosen != 1 || chosen != 2 || chosen != 3) { cin >> chosen; } I got it fixed by doing this: while(chosen < 1 || chosen > 3) Does annyone know whats happening here? Ty in advance!
let me put you out of your misery while(chosen != 1 && chosen != 2 && chosen != 3) { cin >> chosen; } This is a common issue, people translate the human idea in their heads into code: "if its not 1 or 2 or 3 then do xx". But that doesnt work. (chosen != 1 || chosen != 2 || chosen != 3) will always be true. If chosen is say 0 then chosen != 1 is true. So the overall condition is true. If chosen is 1 (which should be the end of your loop) then chosen !=1 is false, BUT chosen != 2 is true so the overall condition is still true (its true if one of the clauses is true, this is what 'or' / '||' means). In fact there is no value for chosen which will cause the overall condition to be false. Chosen is always going to not equal one of 1 or 2 or 3. Your problem came from the looseness of human thought, in conversation we would get what you mean, but not computers. What you wanted was "if its not 1 and its not 2 and its not 3 do xx". Ie while(chosen != 1 && chosen != 2 && chosen != 3)
70,818,107
70,818,409
Identifier not found when calling a function under a function
I trying to develop a program that displays a 12 hour and 24 hour clock at the same time. But whenever I compile, I get a build error saying 'GetAM_PM': identifier not found. I get this error on line 26 in spite of using the same variable from my function parameter. What could be the root of this problem? Here is my code: #include <iostream> #include<ctime> #include<cstdlib> using namespace std; //converting it into 12 hour format int TwelveHourFormat(int twelve_hours) { return (twelve_hours == 0 || twelve_hours == 12) ? 12 : twelve_hours % 12; } //printing the 12 hour format void Display_12_HourFormat(int seconds, int minutes, int twelve_hours) { cout.fill('0'); cout << TwelveHourFormat(twelve_hours) << ":" << minutes << ":" << seconds << " " << GetAM_PM(twelve_hours); } //printing the 24 hour format void Display_24_HourFormat(int seconds, int minutes, int twenty_four_hours) { cout.fill('0'); cout << twenty_four_hours << ":" << minutes << ":" << seconds; } void AddHour(int hour) { hour = (hour + 1) % 24; } void AddMinute(int hour, int min) { if (min == 59) { AddHour(hour); } min = (min + 1) % 60; } void AddSecond(int min, int sec) { if (sec == 59) { AddMinute(min, sec); } sec = (sec + 1) % 60; } // function return AM/PM respect to hour of time string GetAM_PM(int twelve_hours) { return twelve_hours >= 12 ? "PM" : "AM"; } // This method prints the menu options void DisplayMenu() { cout << "Chada Tech Clocks Menu" << endl; cout << "[1] Add one hour" << endl; cout << "[2] Add one minute" << endl; cout << "[3] Add one second" << endl; cout << "[4] Exit program" << endl; } int main() { int seconds, minutes, hours; //obtains current time in seconds time_t total_seconds = time(0); //getting values of seconds, minutes and hours struct tm ct; localtime_s(&ct, &total_seconds); seconds = ct.tm_sec; minutes = ct.tm_min; hours = ct.tm_hour; // Variable declared int option; do { // DisplayMenu function is called DisplayMenu(); cin >> option; // If user input is 1, Clock function is called if (option == 1) { TwelveHourFormat(hours); AddHour(hours); GetAM_PM(hours); Display_12_HourFormat(seconds, minutes, hours); Display_24_HourFormat(seconds, minutes, hours); } // If the option is 2, the Clock function is called else if (option == 2) { AddMinute(minutes, seconds); GetAM_PM(hours); } // If the option is 3, the Clock function is called else if (option == 3) { AddSecond(minutes, seconds); GetAM_PM(hours); } // If the option is 4, exit message prints and application stops running else if (option == 4) { cout << "You have exited the application."; break; } else { cout << "You have entered an invalid input." << endl; } } while (option != 4); }
Just move these lines to the beginning, before any other function: // function return AM/PM respect to hour of time string GetAM_PM(int twelve_hours) { return twelve_hours >= 12 ? "PM" : "AM"; } It is not this case, but if you end up with circular dependency, try to declare the methods in a .h or forward declare the methods in the code.
70,818,250
70,818,521
No default constructor available when I put a struct in an union, but no errors if it is outside
I am trying to put RenderTargetView into an union defined below. But when I try to do that I get the error for the no default constructor available. I am sure there should be default constructor because everything is defined. Also if I put RenderTargetView outside of the union I am no longer getting that error. Does anyone know what is happening here ? Eroror message: GP::Private::ResourceView::ResourceView(void)': attempting to reference a deleted function Function was implicitly deleted because 'GP::Private::ResourceView' has a variant data member 'GP::Private::ResourceView::RTView' with a non-trivial default constructor struct RenderTargetView { static constexpr uint32_t INVALID_INDEX = static_cast<uint32_t>(-1); uint32_t Index = INVALID_INDEX; }; struct FailingStruct { union { RenderTargetView RTView; }; };
A union has default non deleted constructor only if all members of the union have trivial constructors. Same for destructors. Since your struct has a member initializer this means that it doesn't have a trivial constructor this means the union constructor is deleted. You need to create special members for union where you delegate to the active member. Or better yet use std:: variant which has all this created for you. As for why it's simple: a union doesn't know which member is active so it cannot call the appropriate constructor/destructor.
70,818,266
70,818,316
How to parse JSON array from inside an object with rapidjson
The following is a JSON file exported from Tiled Map Editor. { "compressionlevel":-1, "height":32, "infinite":false, "layers":[ { "data":[ A whole bunch of integers in here], "height":32, "id":1, "name":"Tile Layer 1", "opacity":1, "type":"tilelayer", "visible":true, "width":32, "x":0, "y":0 }], "nextlayerid":2, "nextobjectid":1, "orientation":"orthogonal", "renderorder":"right-down", "tiledversion":"1.7.2", "tileheight":32, "tilesets":[ { "firstgid":1, "source":"..\/..\/..\/..\/Desktop\/tileset001.tsx" }], "tilewidth":32, "type":"map", "version":"1.6", "width":32 } And in this C++ block I am trying to parse out the data I actually need. std::ifstream inFStream(filePath, std::ios::in); if(!inFStream.is_open()) { printf("Failed to open map file: &s", filePath); } rapidjson::IStreamWrapper inFStreamWrapper{inFStream}; rapidjson::Document doc{}; doc.ParseStream(inFStreamWrapper); _WIDTH = doc["width"].GetInt(); //get width of map in tiles _HEIGHT = doc["height"].GetInt(); //get height of map in tiles const rapidjson::Value& data = doc["layers"]["data"]; //FAILURE POINT assert(data.IsArray()); When I compile I am able to extract the right value for width and height which are outside of "layers" :[{}] But when that const rapidjson::Value& data = doc["layers"]["data"]; gets called I get a runtime error claiming that document.h line 1344 IsObject() Assertion Failed. Ive been up and down the rapidjson website and other resources and cant find anything quite like this. The next step would be to get the int values stored in "data" and push them into a std::vector but thats not going to happen till I figure out how to get access to "data"
doc['layers'] is an array. const rapidjson::Value& layers = doc["layers"]; assert(layers.IsArray()); for (size_t i=0; i < layers.Size(); i++) { const rapidjson::Value& data = doc["layers"][i]["data"]; assert(data.IsArray()); } UPDATE: Direct access to first data item in layers: const rapidjson::Value& data = doc["layers"][0]["data"]; This only gives you the data for the first item in layers array. If layers have at least one item and you only need the first one, then this will always work.
70,818,401
70,818,547
What difference between passing an instance and a brace-enclosed initializer list to a function?
Say I have the following code. class A { public: float x, y, z; A(float x, float y, float z) : x(x), y(y), z(z) {} }; float average(A a) { return (a.x + a.y + a.z) / 3; } Are there any practical differences between calling the function in these two ways? // a) average(A(1, 2, 3)) // b) average({1, 2, 3})
It depends on the C++ version you are using. Copied (and sligthly modified) from copy elision @ cpprefrence (so, not an exact quote): In C++17 core language specification of prvalues and temporaries is fundamentally different from that of the earlier C++ revisions: there is no longer a temporary to copy/move from. This means that the temporary A you visually show in average(A(1, 2, 3)) is not allowed to be copied or moved since C++17. In fact, there is no temporary. Before C++17, most compilers utilized copy (and move) elision (that has been allowed earlier too, but it wasn't mandatory) to the same effect - but you could not portably rely on it. In C++17, this form of copy elision was made mandatory and is since called Return Value Optimization, or RVO for short. You will also read about Named RVO (or NRVO), which is similar, but does not follow the same rules. It's a bit more complicated and outside the scope of this answer. Before C++17, average(A(1, 2, 3)) could actually mean that a temporary instance of A is created and that the move or copy constructor of the A in the function would have to move (or for a non-movable, copy) the resources from that temporary - which is usually cheap, but doesn't have to be - and it could come with side effects. Some types are neither copyable nor movable. In such cases, the call would not be valid before C++17. In C++17, deleted move and copy constructors does not matter in this case since there is no instance to move or copy from - and the call is therefore undoubtedly valid. When using the brace enclosed initializer list, as you do in this example, not even C++11 is allowed to create (and move) a temporary instance of A. The values are passed directly to the constructor in A(float x, float y, float z). Other that that, I can't spot a difference in your example.
70,818,497
70,818,653
Does C++ standard guarantee that std::vector's underlying pointer initialized as nullptr
According to https://en.cppreference.com/w/cpp/container/vector/data, the underlying pointer is not guaranteed to be nullptr if the size is 0 If size() is 0, data() may or may not return a null pointer. but does that apply to the default initialized std::vector with no elements? or does that simply state that if all elements of the vector are erased, the underlying pointer may not become nullptr? Consider the following line: std::vector<int> fooArr; int* fooArrPtr = fooArr.data(); is it guaranteed that fooArrPtr is equal to nullptr?
No. The standard guarantees that a default-initialised std::vector has size() equal to zero, but that doesn't require that data() will return nullptr. There is nothing in the standard that prevents (and "not preventing" is not equivalent to "requiring") a default-constructed vector having zero .size() and non-zero capacity(). In such a case, it would be feasible for .data() to return a pointer to the allocated memory (which will be non-null, but dereferencing it will still have undefined behaviour since .size() is zero [and allocated capacity is not required to be initialised]). If you want to test if a vector has zero size, use .size() or .empty(). Don't call .data() and compare the result with nullptr.
70,818,746
70,827,795
OpenGL texture coordinates are mirrored when GLM_FORCE_LEFT_HANDED is defined
My engine uses a left-handed coordinate system (y up z forward), so I am defining GLM_FORCE_LEFT_HANDED. However, I have found an issue that all textures are mirrored on the x axis. I tried fixing it by flipping the image on load, and while the image does render correctly after that, the uv coords become aligned to the bottom right instead of the bottom left. GLM_FORCE_LEFT_HANDED on: Left handed coordinates show the image as flipped GLM_FORCE_LEFT_HANDED off: Right handed show image correctly
Alright I figured it out. It was actually my mesh that was the culprit. Not GLM_FORCE_LEFT_HANDED or OpenGL. Each individual face was backward, with the 0,0 uv coordinate in the bottom right corner and 1,1 in the top left. After fixing the mesh the problem has gone away.
70,818,766
70,818,818
Why can't I include the string library in C++?
This is a short one. There's a fatal error: No library titled "string" or something like that. #include <string> using namespace std; int main () { //[insert code here] } It should be correct, I looked how to use strings and this is exactly what to do.
Make sure you are compiling it with a c++ compiler. Using a C compiler for C++ code may produce confusing error messages just like the one you got.
70,818,779
70,818,937
Segmentation fault Binary search Tree
I know there is few questions with a similar title, however I went over them and still couldn't solve my error. This is the BST implementation: struct node { int val; node* left; node* right; }; node* createNewNode(int x) { node* nn = new node; nn->val = x; nn->left = nullptr; nn->right = nullptr; return nn; } void bstInsert(node* &root, int x) { if(root == nullptr) { root = createNewNode(x); return; } if(x < root->val) { if(root->left == nullptr) { root->left = createNewNode(x); return; } else { bstInsert(root->left, x); } } if( x > root->val ) { if(root->right == nullptr) { root->right = createNewNode(x); return; } else { bstInsert(root->right, x); } } } Here is my main: int main() { node *root = nullptr; for (int i = 0; i < 100000; i++) { bstInsert(root, i); } } If I try to insert 10000 elements then it works alright. however when I try to insert 100000 elements I get in the debugger: Signal = SIGSEGV (Segmentation fault) It happens when the value of I in the loop reaches 32469, what am I missing ?
First of all, your Binary Search Tree is Right Skewed Binary tree because the new element will get added as the right most child of existing tree. That said, for every insertion, the recursion will go as deep as the value of i passed to bstInsert() and, for some big value of i, eventually it run out of space, while recursing, and crash. It's not good idea to use recursion for insertion in such a big tree. Better to go for iterative implementation. Additional: Add the check for new operator failure. PS: On my system your code is not crashing for 100000 elements insertion :).
70,818,781
70,818,969
How to create a constructor in source file C++
I have been researching for hours. This simple task is eluding me... Any suggestions of refactoring are encouraged. I am not a C++ person obviously. I've watched all these videos but none of the demo classes have multiple fields. I certainly have not seen a source file that initializes a null array. Links: C++ - Classes - Creating Source files and Header files Buckys C++ Programming Tutorials - 15 - Placing Classes in Separate Files C++ Header Files* How the C++ Linker Works Constructors in C++ How to Write a C++ Class Separating a C++ class into a .h and .cpp files After a few comments I have updated the context of the question Node.h #ifndef NODE_H_ /* INCLUDE GUARD */ #define NODE_H_ #include <iostream> namespace Node{ class Node { private: // PRIVATE FIELDS static const int size = 27; public: // PUBLIC FIELDS Node(bool isWord); // CONSTRUCTOR bool isWord; Node* character[size]{}; void insertme(std::string); // FUNCTION PROTOTYPE int searchme(std::string); // FUNCTION PROTOTYPE }; } #endif // NODE_H_ Node.cpp // SOURCE FILE #include "Node.h" #include <iostream> using namespace std; Node::Node(bool isWord) { /* * This constructor needs to: * set isWord to false * populate Node* character[size] to be filled with null */ }; void insertme(string token){ return; } int searchme(string token){ return 0; } NOTE: this constructor does not throw any errors but it doesn't initialize the member fields the way I need it to // SOURCE FILE #include "Node.h" #include <iostream> using namespace std; Node::Node(isWord) {}; void insertme(string token){ return; } int searchme(string token){ return 0; }
You need to declare a default value for your constructor taking a bool if you want it to be usable without arguments. A constructor without any mandatory arguments is a default constructor. The definition of the class and declaration of its member functions: #pragma once // or a standard header guard class Node { public: Node(bool isWord = false); // this is now a default constructor // other members etc ... }; A possible use of it: #include "Node.h" // where Node is defined int main() { Node x; // default construct a `Node` } The definition of the constructor in Node.cpp: #include "Node.h" #include <ios> #include <iostream> Node::Node(bool isWord) { // note, no default values here std::cout << std::boolalpha << isWord << '\n'; } Output if compiled and linked: false Demo
70,818,894
70,819,147
How to pick up elements from std::vector<struct> quickly?
I have a struct MyStruct which have some elements (including int value1), and a std::vector<MyStruct>. How can I pick up all value1 from each MyStruct and have a std::vector<int> which is the vector of value1. No write will be operated on the new vector. The following is possible but the copy is needed. Is there any solution to avoid it? struct MyStruct{ int value1; int value2 }; std::vector<MyStruct> myStruct = func1(); std::vector<int> ans; for (auto i:myStruct) { ans.push_back(i.value1); } func2(ans); //func2 (const vector<int>&); The struct structure is just an example. The actual structure I use is much more complex.
I believe a more optimal solution would be to change the func2 to take in a &std::vector<MyStruct> as an argument by reference so that no copy is made. Then you can just access each element by myStruct[i].value1.
70,818,988
70,819,229
What are "extern char condition tricks"?
I was reading the GCC documentation on C and C++ function attributes. In the description of the error and warning attributes, the documentation casually mentions the following "trick": error ("message") warning ("message") If the error or warning attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, an error or warning (respectively) that includes message is diagnosed. This is useful for compile-time checking, especially together with __builtin_constant_p and inline functions where checking the inline function arguments is not possible through extern char [(condition) ? 1 : -1]; tricks. While it is possible to leave the function undefined and thus invoke a link failure (to define the function with a message in .gnu.warning* section), when using these attributes the problem is diagnosed earlier and with exact location of the call even in presence of inline functions or when not emitting debugging information. There's no further explanation. Perhaps it's obvious to programmers immersed in the environment, but it's not at all obvious to me, and I could not find any explanation online. What is this technique and when might I use it?
I believe the premise is to have a compile time assert functionality. Suppose that you wrote extern char a[(condition) ? 1 : -1]; If condition is true, nothing happens and the line compiles to nothing. The extern makes sure that a doesn't use any memory. However, if condition is false, a is declared as an array of negative length, and you get a compile time error. You probably wrap it in a macro and have something similar to static_assert #define STATIC_ASSERT(condition) extern char a[(condition) ? 1 : -1]
70,819,005
70,819,061
C++ : Can a thread be executed without calling the join() function in the main function?
Please help me with a simple question about the output of the following code. I thought that a thread is executed only when the join() or detach() function is called. So, I expect the output to print only "pause of 2 seconds ended , ID = 59306", and not to print "pause of 1 seconds ended , ID = 10218" because I thought that only thread 2 would be executed, and thread 1 would NOT be executed. But, I was wrong. In reality, the output actually prints both of the lines mentioned above, which means both thread 1 and 2 are executed. Is it true ? Would you please explain to me how the code actually execute both threads ? ========================== #include <iostream> // std::cout #include <thread> // std::thread, std::this_thread::sleep_for #include <chrono> // std::chrono::seconds void pause_thread(int n) { std::this_thread::sleep_for (std::chrono::seconds(n)); std::cout << "pause of " << n << " seconds ended , ID = " << std::this_thread::get_id() << std::endl; } int main() { std::cout << "Spawning 2 threads...\n"; std::thread t1 (pause_thread,1); std::thread t2 (pause_thread,2); std::cout << "Done spawning threads. Now waiting for them to join:\n"; //t1.join(); t2.join(); //t1.detach(); //t2.detach(); std::cout << "All threads joined!\n"; return 0; } Actual Output : Spawning 2 threads... Done spawning threads. Now waiting for them to join: pause of 1 seconds ended , ID = 10218 pause of 2 seconds ended , ID = 59306 All threads joined! =================== Update: Thanks to all comments and answers from everyone. Now, I understand my incorrect logic because I mistakenly thought that a thread were executed only when the join() or detach() function is called. I realize that a thread is executed as soon as it is created without the need to call join() or detach(). join() : In the main() function, after we call join() on a thread, the main() function will be blocked until the thread completes. After the thread completes, the main() function will resume, and the output from the thread will be shown along with any remaining output from the main() function. detach() : In the main() function, if we call detach() on a thread, then, both the main() function and thread can run concurrently, and they are not blocked by each other or do not depend on each other in any way. In this case, if the main() function finishes before the detached thread completes, then we can only see the output from the main() function and NOT from the detached thread. However, if the detached thread finishes before the main() function completes, then we can see the output from both the thread and the main() function.
Threads start execution not when .join() is called on them, but when they are constructed. .join() is used to block the calling thread's execution until the thread being joined to has finished execution. It is typically required to join all threads before main() exits for the reason you observed: When main() reaches the return statement, the scope of the std::thread objects is left. If neither .join() or .detach() has been called on the std::thread managing a thread at this point, the std::thread's destructor is going to call std::terminate() which (by default) aborts the whole program's execution. Even if you detach the threads instead of joining them, when main() didn't block long enough via calls to .join() and exits before the threads have finished their output, there is a problem. After exiting main(), static storage duration objects are destroyed. One such object is std::cout. When the threads then try to output via std::cout after their wait, it is already destroyed and the program has undefined behavior. Also note that detaching t1 and joining t2 isn't safe either, although the waiting times seem to suggest that. When exactly threads are scheduled for execution is up to the operating system. It could happen that thread t2 finishes before t1, in which case the issue mentioned above applies again, causing the program to again have undefined behavior.
70,819,502
70,819,752
What is the lpstr filter for folders?
I am trying to open a dialog box where the user selects a certain folder on pure C++, no .Net framework or C#, and am struggling to find how the lpstr would filter everything but directories. I am currently using the OPENFILENAME function. I tried filtering to .dir, but it does not work. Anyone know the actual extension or any solutons?
The OPENFILENAME struct is used with the old GetOpenFileName() Common Dialog Box, which can't be used to select a folder. It is simply not designed for that purpose. You need to use SHBrowseForFolder() instead, or in Vista+ you can (and should) use the newer IFileOpenDialog Common Item Dialog with the FOS_PICKFOLDERS option enabled.
70,819,577
70,819,673
Why do I have a memory leak in my c++ code?
I'm new to c++ and I have code that compiles but won't publish to linux because it says I have a memory leak in the error. Please help me find the error in the code. Linux uses valgrind, which finds the leak. Please help me find the error and fix it. Output with memory leak: ==6858== Memcheck, a memory error detector ==6858== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al. ==6858== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info ==6858== Command: ws ==6858== Enter the following Data: ---------------------- lukE sky fett feT Jack ! ---------------------- Star Wars phone direcotry search ------------------------------------------------------- Enter a partial name to search (no spaces) or enter '!' to exit > lukE Luke Skywalker: (301) 555-0630 Enter a partial name to search (no spaces) or enter '!' to exit > sky Luke Skywalker: (301) 555-0630 Enter a partial name to search (no spaces) or enter '!' to exit > fett Jango Fett: (905) 555-6016 Boba Fett: (905) 555-9382 Enter a partial name to search (no spaces) or enter '!' to exit > feT Jango Fett: (905) 555-6016 Boba Fett: (905) 555-9382 Enter a partial name to search (no spaces) or enter '!' to exit > Jack Enter a partial name to search (no spaces) or enter '!' to exit > ! Thank you for using Star Wars directory. ---------------------------------- Broken Phone Book phone direcotry search ------------------------------------------------------- badDataFile.txt file not found! Thank you for using Broken Phone Book directory. ==6858== ==6858== HEAP SUMMARY: ==6858== in use at exit: 568 bytes in 1 blocks ==6858== total heap usage: 384 allocs, 383 frees, 88,684 bytes allocated ==6858== ==6858== 568 bytes in 1 blocks are still reachable in loss record 1 of 1 ==6858== at 0x4C29F73: malloc (vg_replace_malloc.c:309) ==6858== by 0x578CC4C: __fopen_internal (in /usr/lib64/libc-2.17.so) ==6858== by 0x40114B: sdds::phoneDir(char const*, char const*) (in /home/kshiman/OOP244/DIY/ws) ==6858== by 0x40156E: main (in /home/kshiman/OOP244/DIY/ws) ==6858== ==6858== LEAK SUMMARY: ==6858== definitely lost: 0 bytes in 0 blocks ==6858== indirectly lost: 0 bytes in 0 blocks ==6858== possibly lost: 0 bytes in 0 blocks ==6858== still reachable: 568 bytes in 1 blocks ==6858== suppressed: 0 bytes in 0 blocks ==6858== ==6858== For lists of detected and suppressed errors, rerun with: -s ==6858== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) this is structure: struct record { char name[50]; int prefix; int area; int number; }; this is the main file: #include "Phone.h" using namespace std; using namespace sdds; #define _CRT_SECURE_NO_WARNINGS int main() { if (Name == "!") break; phoneDir("Star Wars", "phones.txt"); return 0; }
Here, if (Name == "!") break; you are breaking the outter loop, hence exiting the code without closing the file. This will leak memory. You should close the file before the break.
70,819,960
70,823,405
How to turn an integer into vector and then turn that vector into string in C++
I want to take an integer and turn it into an array and then store it into a string in C++. But I do not know how to turn an integer into an array and then store it into a string. I am still learning C++, so help me, please. That's how I want it to be done: #include<iostream> #include<vector> using namespace std; int main() { int number = 3215; //store the number into vector vector<int> numbers; //vector[0]=3 //vector[1]=2 //vector[2]=1 //vector[5]=5 //and then store it into string string str; //like this //str=3215 return 0; } Please help me and show the code as well with explanation Edit: I have some data to work with integer values with every digit which I can solve my own but for that, I need to first turn the integer into vector and return it as a string. THat's why I want to know how to turn integer into vector first and the that vector into string
Here you are: #include <iostream> #include <vector> #include <cmath> #include <string> #include <algorithm> #include <iterator> int main() { int n; std::cin >> n; std::vector<int> split(static_cast<int>(std::log10(n)) + 1); auto royal_10 = split.rbegin(); auto cpy{ n }; do { *royal_10++ = cpy % 10; } while ((cpy /= 10) != 0); std::string ret; ret.reserve(split.size()); std::transform(split.cbegin(), split.cend(), std::back_inserter(ret), [](int const dig) { return dig + '0'; }); return 0; }
70,819,990
70,820,014
How to set the specific value to the concept template class explicit instantiation?
I have codes as follow: #include <concepts> //Fibo Begins template <std::unsigned_integral num> struct Fibo { constexpr static std::size_t value = Fibo<num - 1>::value + Fibo<num - 2>::value; }; template <> struct Fibo<1> { constexpr static std::size_t value = 1; }; template <> struct Fibo<2> { constexpr static std::size_t value = 1; }; //Fibo ends Compiler give out an error that argument 1 and 2 is invaild What's going on here? How can I fix it ?
First, the syntax you are using is for a constrained type template parameter, not a non-type template parameter with constrained type. So the compiler is complaining that it expects a type as template argument, not a value. For a non-type template argument with constrained type it should be std::unsigned_integral auto num instead. But then 1 and 2 have type int. They are not unsigned and your type constraint correctly rejects them. 1u and 2u would for example be unsigned integers and accepted by the template parameter. For a non-type template parameter with a placeholder type not only the value provided, but also the type, is significant. It looks though as if you really want the type to be std::size_t, not any unsigned integral. So maybe just use that as type for the non-type template parameter instead of the constraint.
70,820,047
70,820,075
Getting wierd output in recursion code! Even though logic seems to be correct
I've been trying to attempt a question on recursion pattern and it is pretty easy one but I am not able to getting why I am getting such an unexpected output. I traced the variables and parameters in callstack and my logic seems to be right but still it is printing random numbers. #include <bits/stdc++.h> using namespace std; vector<int> pattern(int); int main() { int n; cin >> n; vector <int> ans = pattern(n); for (int u: ans) { cout << u << " "; } cout << "\n"; } vector<int> sol; vector<int> pattern(int N) { if (N <= 0) { // cout << "stopped" << endl; sol.push_back(N); return sol; } sol.push_back(N); pattern(N-5); sol.push_back(N); } i/p: 10 expected o/p: 10 5 0 5 10 but it is giving this result: 6422500 1997786416 -1172770555 0 6422508 1997703885 -1 1997899634 0 0 4199136 2576384 0 32 0 0 0 10672 726272 791648 826264 57158026 0 35651584 0 590440 36175880 524296 590376 36175880 524298 524832 35651584 9 655944 34603080 4718603 721424 34604104 4718597 328208 34604104 71303179 262672 34603080 4718599 262672 34604096 71827463 197252 58785856 -2143289343 66305 34635840 71958539 66434 50495552 -2143289343 524840 38273024 524295 721424 34603016 524293 721424 51512330 -2080374783 560 34866184 3 66322 34635784 655371 721424 50397184 -2147287039 66305 ..... [Truncated]```
You are missing a return statement from pattern() function. vector<int> pattern(int N) { if (N <= 0) { // cout << "stopped" << endl; sol.push_back(N); return sol; } sol.push_back(N); pattern(N-5); sol.push_back(N); return sol; // <--------- this was missing } Let N = 10, so pattern(10) will be called, then: sol = {10} pattern(5) sol = {10, 5} pattern(0) -> sol = {10, 5, 0} -> return sol -> but you don't store return value of pattern anywhere, so the return value is lost sol = {10, 5, 0, 5} function returns garbage, but that's also not captured anywhere sol = {10, 5, 0, 5, 10} function returns garbage which is captured by ans. Actually, your function isn't required to return a vector at all, since your vector is declared as global. You could have void return type and it would work without any return statement. The below code works fine: #include <iostream> #include <vector> using namespace std; vector<int> sol; void pattern(int); int main() { int n; cin >> n; pattern(n); for (auto& u: sol) { cout << u << " "; } cout << "\n"; } void pattern(int N) { if (N <= 0) { // cout << "stopped" << endl; sol.push_back(N); return; } sol.push_back(N); pattern(N-5); sol.push_back(N); } Also a side note, it's recommended by many people to not to use: #include <bits/stdc++.h> Instead use individual includes: #include <iostream> #include <vector>
70,820,127
70,820,232
std::construct_at on top of existing object skipping re-initialization of some fields
In the following program, in a constant expression, a temporary object of A is created with all fields initialized, and then function f creates another object of A at the same address, skipping (re)initialization of the field x, which is read afterwards: #include <memory> struct A { int x; constexpr A() {} constexpr A(int xx) : x(xx) {} }; constexpr int f(A && a) { std::construct_at<A>(&a); return a.x; } static_assert( f(A{5}) == 5 ); //ok in GCC only GCC accepts it just fine. But other compilers complain, e.g. Clang: note: read of uninitialized object is not allowed in a constant expression return a.x; ^ Demo: https://gcc.godbolt.org/z/87zrEb7q7 Indeed x is not initialized in std::construct_at<A>(&a), but it was initialized in A{5}. Which compiler is right here?
I'm convinced this is UB, and GCC is wrong. std::construct_at<A>(&a) creates a new A object, and thus a new int x member in it. That new object isn't initialized. For this to be legal, there would have to be a special rule that uninitialized objects may get values based on the contents of memory they occupy, and I don't think such rule exists. [basic.indet] doesn't mention it.
70,820,275
70,842,385
Vulkan image incompatibility, is there a nice way to check which parameters are incompatible?
My validation errors are returning the following error: Message ID name: VUID-VkImageCreateInfo-imageCreateMaxMipLevels-02251 Message: Validation Error: [ VUID-VkImageCreateInfo-imageCreateMaxMipLevels-02251 ] Object 0: handle = 0x1867f53a780, name = Logical device: NVIDIA GeForce GTX 1070, type = VK_OBJECT_TYPE_DEVICE; | MessageID = 0xbebcae79 | vkCreateImage(): Format VK_FORMAT_R8G8B8A8_SRGB is not supported for this combination of parameters and VkGetPhysicalDeviceImageFormatProperties returned back VK_ERROR_FORMAT_NOT_SUPPORTED. The Vulkan spec states: Each of the following values (as described in Image Creation Limits) must not be undefined : imageCreateMaxMipLevels, imageCreateMaxArrayLayers, imageCreateMaxExtent, and imageCreateSampleCounts (https://vulkan.lunarg.com/doc/view/1.2.198.1/windows/1.2-extensions/vkspec.html#VUID-VkImageCreateInfo-imageCreateMaxMipLevels-02251) Severity: VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT I know exactly the place in the code that's causing this, however I don't know which combination of parameters is at fault. Is there a way to get the driver to indicate: "Your image is format x which is incompatible with usage type y" or something like that?
If some parameters are clashing, then ask https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues for improved error reporting. There should ideally be appropriate error message. But if the GPU simply does not support given combination of parameters, then there is nothing that can be done. It is meaningles to ask "why don't you support X". They simply don't, because it is not implemented or not implementable on given GPU\driver.
70,820,639
70,820,954
Can anyone explain this code? I do not understand the working of not1() and ptr_fun()
Can anyone explain the working of this function? string rightTrim(const string &str) { string s(str); s.erase(find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end()); return s; } I don't know the working of not1() and ptr_fun(). Can anyone provide me with a good explanation for this code? PS: I know, this code removes any white spaces from the end of the string.
The question is essentially What is not1(ptr_fun<int, int>(isspace))? Short answer You should use std::not_fn(isspace) instead, which clearly states it is a "thing" that expresses the idea that "something is not a space".(¹)(²) Wordy answer It is a predicated that asks if its input is not a space: if you apply it to 'a' you get true, if you apply it to ' ', you get false. However, one the not in the paragraph above explains the reason why the code has not1, but it doesn't say anything about ptr_fun. What is that for? Why couldn't we just write not1(isspace)? Long story short, not1 is an old generation helper function which was deprecated in C++17 and removed in C++20. It relies on the argument that you pass to it to have a member type named argument_type, but isspace is a free function, not an object of a class providing such a member, so not1(isspace) is ill formed. ptr_fun came to the rescue, as it can transform isspace in an object which provides the interface that not1 expects. However, ptr_fun was deprecated even before not1, in C++11, and removed in C++17. The bottom line is therefore that you should not use either of those: you don't need ptr_fun anymore, and you can use not_fn as a more usable alternative to not1. You can indeed just change not1(ptr_fun<int, int>(isspace)) to std::not_fn(isspace), which also reads much more like "is not a space". (¹) By the way, stop using namespace std;. It's just the wrong thing to do. (²) Yes, even if you have to stick to C++14, don't use std::not1. In C++14 you already have generic lambdas, so you can define a quasi-not_fn yourself (working example): auto not_fn = [](auto const& pred){ return [&pred](auto const& x){ return !pred(x); }; };
70,820,698
70,821,163
Ensuring compilation error while passing null pointer to a function
Let's say that I have a function which takes in pointers. int functionA(int* a, int* b) { ... } I can add null checks inside functionA. Is there a way that I can ensure that an error occurs on the compile time whenever nullptr is passed as a parameter.
Is there a way that I can ensure that an error occurs on the compile time whenever nullptr is passed as a parameter. If you specifically mean the nullptr keyword, then sort of. You can provide overloads that would be chosen in that case, and define them deleted. This works as long as you don't explicitly bypass the overloading by casting for example. int functionA(int*, std::nullptr_t) = delete; int functionA(std::nullptr_t, int*) = delete; // ... functionA(&i, &j) // OK functionA(nullptr, &i); // error functionA(&i, nullptr); // error functionA(nullptr, nullptr); // error or NULL This will require adding overloads for integers in addition to the previous overloads: int functionA(int*, int) = delete; int functionA(int, int*) = delete; // ... functionA(NULL, &i); // error functionA(&i, NULL); // error functionA(NULL, NULL); // error If you mean any pointer with null value, then that cannot be done because the values of function arguments cannot generally be known at compile time. If your goal is to not use the pointers as iterators, then it would be safer and more convenient to pass references instead.
70,820,998
70,821,048
Why are the addresses of these two local variables the same?
I have defined a function here that accepts an array as a parameter void print(char ch[]); When I call the function and give it the array as an argument int main(){ char ch[10]; print(ch); } And I print the addresses of these two variables in two different functions, #include <stdio.h> void print(char ch[]) { printf("address of ch is %d\n",ch); } int main() { char ch[10]; print(ch); printf("address of ch is %d\n",ch); return 0; } the address of the array in the main function must be different from the address of the array as a parameter in the function I defined, but it is the same. Why? And whether the address of a variable can be negative? Thanks for taking the time to read this question.
For starters to output a pointer you need to use the conversion specifier %p instead pf the conversion specifier %d. Otherwise the call of printf invokes undefined behavior. printf("address of ch is %p\n", ( void * )ch); Secondly within the function this call of printf does not output the address of the variable ch itself. It outputs the address of the first element of the array pointed to by the pointer expression ch. As the array is not moved within memory then you will get the same value of the address. To output the address of the function parameter you need to write void print(char ch[]) { printf("address of ch is %p\n", ( void * )&ch); } Pay attention to that in this call print(ch); the array is implicitly converted to pointer to its first element. And the compiler adjusts the function parameter having an array type to pointer to the array element type void print(char *ch) { There is a difference between these two calls of printf in main where the source array is declared and within the function printf("address of ch is %p\n", ( void * )ch); printf("address of ch is %p\n", ( void * )&ch); Within the function the first call outputs the address of the first element of the array pointed to by the pointer ch that is the address of the extent of memory occupied by the array. The second call outputs the address of the local variable ch itself having the type char * (as pointed above). In main these calls outputs the same value that is the address of the extent of memory occupied by the array. The first call outputs the address of the first element of the array and the second call outputs the address of the array as a whole object. The both values are the initial address of the extent of memory occupied by the array.
70,821,003
70,821,069
How to modify the same variable in different classes and modify it?
I have many function definitions which I have placed in different cpp files with function declarations in their respective .h files. I have a set of a variables which I have placed in a .h file. These variables need to modified by different functions. I am using static to keep the changes from each function, but I heard it is a bad coding practice. How else to do it ? For eg - variables.h class variable{ static int x; static int y; }; function1.h class function(){ public: void function1(); } similar for function 2 function 1.cpp void function1(){ // does something with x and y (used as (variable::x=2;variable::y=3) } function2.cpp void function2(){ // does something with x and y (used as variable::x+=2;variable::y+=2) } main.cpp int variable::x; int variable::y; int main(){ obj.function1(); (obj is object of function1 class) obj2.function2(); (obj2 is object of function2 class) cout << variable::x << variable::y << endl; } I was was using different objects in different cpp files but changes in one function were not reflecting in other. How it use it please help?
You can simply move these variables into another class: struct Shared { int x; int y; }; Now you can pass an instance to this class as parameter to your function, this is called dependency injection: void foo(Shared& shared) { shared.x = 4; shared.y = 2; } This is better because you don't have any global state anymore. You could use the function multiple times independent from each other by referencing a different instance of the Shared class. It is very common to take this a step further by "injecting" the instance in the constructor of that class. This is helpful if the instance of that class should always reference the same instance: struct Foo { Shared& m_shared; Foo(Shared& shared) : m_shared(shared) { } void foo() { m_shared.x = 4; m_shared.y = 2; } };
70,821,399
70,821,444
Is Undefined Behavior To Using Invalid Iterator?
Consider this code: #include <iostream> #include <string> #include <map> int main() { std::map<std::string, std::string> map = { { "ghasem", "another" } }; std::cout << map.find("another")->second << std::endl; std::cout << map.size() << std::endl; } It will be compiled and run successfully(the process return value is 0), but we couldn't see the output of map.size(). Neither -fsanitize=address nor -fsanitize=undfined reports any problem. I compiled with GCC-11.2.1 and Clang-13.0.0, both are the same. And running the code step by step using GDB-11.1-5 will not help and all the steps will be run successfully. But if I reorder the last two lines: #include <iostream> #include <string> #include <map> int main() { std::map<std::string, std::string> map = { { "ghasem", "another" } }; std::cout << map.size() << std::endl; std::cout << map.find("another")->second << std::endl; } I will get a Segmentation Fault and now ASAN could report the error. And my question here is: Is the code cause some sort of Undefined Behavior? How could I detect those errors? Environment: OS: Fedora 35 Compiler(s): GCC 11.2.1 Clang 13.0.0 Additional Compiler Flags: Debugger: GDB 11.1-5
There is no key comparing equal to "another" in the map. Therefore map.find("another") will return the .end() iterator of the map. Dereferencing this iterator in ->second is then undefined behavior since end iterators may not be dereferenced. Your code should check that the iterator returned from find is not the end iterator, i.e. that an element has been found. In terms of debugging, if you are using libstdc++ as standard library implementation (which is the case with GCC and potentially with Clang), you can use -D_GLIBCXX_DEBUGon the compiler invocation to enable debug assertions in the standard library implementation which will detect this issue.
70,821,434
70,821,502
C++ variadic template syntax within dependent scope
I have a problem with real-world code and have replicated the problem with the following sample code. #include <iostream> #include <tuple> using namespace std; struct Identity { template <typename... T> static std::tuple<T...> Apply(T... val) { return std::tuple(val...); } }; template <typename F, typename... T> std::tuple<T...> Apply(T... t) { return F::Apply<T...>(t...); } int main() { const auto t = Apply<Identity>(1., 2., 3.); cout << std::get<0>(t); cout << std::get<1>(t); cout << std::get<2>(t); return 0; } Compilation error: main.cpp:26:22: error: expected primary-expression before ‘...’ token return F::Apply<T...>(t...); ^~~ main.cpp:26:22: error: expected ‘;’ before ‘...’ token main.cpp:26:22: error: expected primary-expression before ‘...’ token If I remove <T...> from the problematic statement, i.e. return F::Apply(t...);, and let the compiler deduce the type, it works. However, in my real world code I need to specify the types. What is the correct syntactical sugar to specific the types and satisfy the compiler?
You are missing one keyword. You need: return F::template Apply<T...>(t...); And it'll be fine. This error message is not the clearest one. :) You can find an explanation here if you are interested in the details: Where and why do I have to put the "template" and "typename" keywords?
70,821,456
70,824,472
Exception handler catch(...) in C++
I understand that exception handler catch(...) in C++ handles any type of exception. I am wondering what happens if it has to handle an exception that is of some class type - is the object of that class passed to this handler by reference or by value? This is the code that could help in understanding this. When the exception of type B is thrown in "Inner try", an unnamed temporary object of class B is created with the default constructor of class B. When I run this program, copy constructor of class B doesn't get called at all, and this unnamed temporary object of class B is destroyed only after executing "Outer try 3", which means that object was propagated backwards all the way to the "Outer try 3". So my guess is that objects are passed by reference to the catch(...) handler, but I wanted to see if this is correct reasoning. #include <iostream> using namespace std; class A { public: A() { cout << "Default constructor of class A" << endl; } A(const A& a) { cout << "Copy constructor of class A" << endl; } A(A&& a) noexcept { cout << "Move constructor of class A" << endl; } ~A() { cout << "Destructor of class A" << endl; } }; class B { public: B() { cout << "Default constructor of class B" << endl; } B(const B& b) { cout << "Copy constructor of class B" << endl; } B(B&& b) noexcept { cout << "Move constructor of class B" << endl; } ~B() { cout << "Destructor of class B" << endl; } }; int main() { try { try { try { try { throw A(); } catch (A a) { cout << "Inner try" << endl; throw B(); } } catch (...) { cout << "Outer try 1" << endl; throw; } } catch (...) { cout << "Outer try 2" << endl; throw; } } catch (...) { cout << "Outer try 3" << endl; } }
When you throw an exception, the exception object is created from the operand to throw. It is an object stored in an unspecified way. When a matching handler for the exception is reached and the handler is not ..., then the handler's parameter is initialized from the exception object. Essentially, if you declare a catch parameter as a non-reference type, you are getting a copy of the exception object (or of a base class subobject) in the handler. This is what you see in the A handler and why there is a call to the copy constructor. The copy lives until the handler exits. If you declare the parameter a reference type, then you will get a reference to the exception object and it will always refer to the same object if you rethrow the exception. Rethrowing with throw; does not actually do anything with the parameter of the catch clause. It simply causes the exception handling to continue searching the catch clauses and stack unwinding. The exception object is still the same. Nothing about this changes if the handler is catch(...). There is no variable (reference or not) to initialize in the handler, but throw; will rethrow and continue the search for a handler with the same exception object. When a handler exits without rethrowing the exception, then the exception object is destroyed. This happens at the end of your outer-most catch for the B exception object and at the end of the inner-most catch for the A exception object. (You get two destructor calls to A, one for the catch parameter and one for the exception object.)
70,821,514
70,823,638
Inner product of compile-time coefficients and sequence of values
Looking to calculate the inner product of a series of floating point values and corresponding coefficients (given that the coefficients are known at compile-time). template <uint64_t Divisor, uint64_t... Coefficients> static consteval std::array<double, sizeof...(Coefficients)> createCoefficients() { double coeff[] = {Coefficients...}; for (auto& c : coeff) c /= Divisor; return std::to_array(coeff); } template <uint64_t Divisor, uint64_t... Coefficients> static constexpr auto inner_product(std::floating_point auto... values) requires(sizeof...(values) == sizeof...(Coefficients)) { constexpr auto coeff = createCoefficients<Divisor, Coefficients...>(); std::initializer_list<double> il({values...}); return std::inner_product(coeff.begin(), coeff.end(), il.begin(), 0); } I would like to simplify this as I have a feeling the interface is not as clean as I would like. Are there any improvements that could be made here?
This appears way too complicated. Something along these lines perhaps: template <uint64_t Divisor, uint64_t... Coefficients> static constexpr auto inner_product(std::floating_point auto... values) { return ((values * Coefficients / Divisor) + ...); } Demo
70,821,856
70,829,598
C++ trivial function: return value type doesn't match the function return type: ternary operator
I cannot understand why would Visual Studio Intellisense complain. In the code: int absolute_value(int x) { return x > 0 ? x : - x; } It underlines x in return x with the message: return value type doesn't match the function return type.
My environment is win10, vs2022. I tested the code you posted, the code works fine, I suggest you repair your Visual Studio or download it again. #include<iostream> using namespace std; int absolute_value(int x) { return x > 0 ? x : -x; } int main() { cout << absolute_value(-6); }
70,821,987
70,822,384
MultiIndex containers -- offering vector and set access
I have an application where, first, an std::vector<int> object is generated. Then, some operations need to be performed on this object viewed as an std::set<int> where the order does not matter and repetitions don't count. At present, I explicitly construct an object of type std::set<int> from the std::vector<int> object. An example is presented below: #include <cstdio> #include <set> #include <vector> void printset(std::set<int>& Set) { printf("Printing Set Elements: "); for (std::set<int>::iterator siter = Set.begin(); siter != Set.end(); ++siter) { int val = *siter; printf("%d ", val); } printf("\n"); } void printvec(std::vector<int>& Vec) { printf("Printing Vec Elements: "); for (size_t i = 0, szi = Vec.size(); i < szi; ++i) { int val = Vec[i]; printf("%d ", val); } printf("\n"); } int main() { std::vector<int> VecInt{ 6, 6, 5, 5, 4, 4 }; std::set<int> SetInt(VecInt.begin(), VecInt.end()); printvec(VecInt); printset(SetInt); } I am trying to see if I can use Boost.MultiIndex for this purpose. One introduction to Boost.MultiIndex states: Boost.MultiIndex can be used if elements need to be accessed in different ways and would normally need to be stored in multiple containers. Instead of having to store elements in both a vector and a set and then synchronizing the containers continuously, you can define a container with Boost.MultiIndex that provides a vector interface and a set interface. and this is precisely what I am doing (using multiple containers and then creating one from the other constantly) while I would like to create a (multi-index) container once and then provide a vector interface and a set interface. On looking through various examples, for e.g., here and here, it is not clear how those examples can be modified to the code example above. Ideally, I would like to do the following in the code example above: MultiIndexContainer vec_set_container; vec_set_container.push_back(6);//or anything equivalent for the MultiIndexContainer vec_set_container.push_back(6); vec_set_container.push_back(5); vec_set_container.push_back(5); vec_set_container.push_back(4); vec_set_container.push_back(4); printvec(vec_set_container.Some_Function_That_Exposes_Vector_Interface()); printset(vec_set_container.Some_Function_That_Exposes_Set_Interface()); How can this be accomplished using Boost.MultiIndex ?
Random access index would match the "vector" interface. An ordered unique index would match the "set" interface. However, if you have a unique index, this will prevent insertion of duplicates. So, you would get: Live On Compiler Explorer #include <boost/multi_index/identity.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/random_access_index.hpp> #include <boost/multi_index_container.hpp> #include <fmt/ranges.h> namespace bmi = boost::multi_index; using Table = bmi::multi_index_container< // int, bmi::indexed_by< bmi::random_access<bmi::tag<struct asVector>>, bmi::ordered_unique<bmi::tag<struct asSet>, bmi::identity<int>>>>; int main() { Table data{ 6, 6, 5, 5, 4, 4 }; fmt::print("As vec {}\nAs set {}\n", // data.get<asVector>(), // data.get<asSet>()); } Printing As vec {6, 5, 4} As set {4, 5, 6} Now, I think the "best" you could do with this is to make the order index non-unique (so, mimicking a std::multiset instead of std::set): Live On Compiler Explorer bmi::ordered_non_unique<bmi::tag<struct asSet>, bmi::identity<int>> Printing As vec [6, 6, 5, 5, 4, 4] As set {4, 4, 5, 5, 6, 6} If you want to traverse unique elements, using a range adaptor would be minimally costly: Using Boost Live fmt::print("As vec {}\nAs set {}\n", // data.get<asVector>(), // data.get<asSet>() | boost::adaptors::uniqued); Using RangeV3 Live fmt::print("As vec {}\nAs set {}\n", // data.get<asVector>(), // data.get<asSet>() | ranges::views::unique); Using Standard Ranges; I couldn't make this work but it should really be something like std::ranges::unique(data.get<asSet>()) All printing As vec {6, 6, 5, 5, 4, 4} As set {4, 5, 6} Other Ideas If you don't require random access, then sequenced index might be preferrable for you. And note that this interface comes with the handy unique() and sort() methods (just like std::list). UPDATE To The Comments Here's a rolled-in-one response to the comments: Live On Compiler Explorer #include <boost/multi_index/identity.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/sequenced_index.hpp> #include <boost/multi_index_container.hpp> #include <fmt/ranges.h> #include <random> namespace bmi = boost::multi_index; template <typename T> using ListSet = bmi::multi_index_container< // T, bmi::indexed_by< bmi::sequenced<bmi::tag<struct byInsertion>>, // bmi::ordered_unique<bmi::tag<struct Ordered>, bmi::identity<T>> // >>; int main() { ListSet<int> data; std::mt19937 prng{99}; // "random" seed for (std::uniform_int_distribution d(1, 10); data.size() < 5;) { int el = d(prng); if (auto [it, unique] = data.push_back(el); not unique) { fmt::print("Element {} duplicates index #{}\n", el, std::distance(begin(data), it)); } } fmt::print("By insertion {}\nOrdered {}\n", data, data.get<Ordered>()); } Prints Element 9 duplicates index #3 Element 8 duplicates index #1 By insertion [7, 8, 5, 9, 1] Ordered {1, 5, 7, 8, 9}
70,822,270
70,828,426
How to rewrite a function from C++ to Python that converts a number from any number system to the decimal system
I have a problem. I have a function in cpp that converts a number from any number system to decimal. But I need a function like this in Python. I just don't know how to rewrite it to work in Python. And I can't use the built-in functions that exist in a given language to replace a number. This is function in cpp and I need convert it to Python int from_any_to_10(string number, int system) { int x; int p = 1; int result = 0; for (int k = number.length() - 1; k >= 0; k--) { if (number[k] <= '9' && number[k] >= '0') { x = number[k] - 48; } else { x = number[k] - 55; } result = result + p * x; p = p * system; } return result; } My code in Python looks like this: def from_any_to_10(number, system): x = int() p = 1 result = 0 for k in range(len(number) - 1, len(number) >= 0, -1): if number[k] <= '9' and number[k] >= '0': x = number[k] - 48 else: x = number[k] - 55 result = result + p * x p = p * system return result But, When I compile code in Python I get this errors: File "C:\Users\LAPTOP\Desktop\Python\_INFA\main.py", line 17, in from_any_to_10 x = number[k] - 48 TypeError: unsupported operand type(s) for -: 'str' and 'int' I don't know how to rewrite it to work in Python. Sorry for my bad English.
In order to convert a number to decimal number system. We can iterate over the number from the end and take each number then multiply the number with number system to the power of its place from the last and sum them all. C++ #include <iostream> #include <algorithm> #include <string> #include <functional> #include <cctype> using namespace std; //converts any number system to decimal number system int from_any_to_10(string number, int system){ //converting string to uppercase std::transform(number.begin(), number.end(), number.begin(), std::ptr_fun<int, int>(std::toupper)); int x; int p=1;//stores power value int result=0; //iterating over numbers in reverse order for(int k=number.length()-1; k>=0; k--){ if(number[k]<='9' && number[k] >='0') x=number[k]-48; else x=number[k]-55; result+=p*x; p*=system; } return result; } int main(){ cout<<from_any_to_10("125a",16)<<endl; cout<<from_any_to_10("1011",2)<<endl; cout<<from_any_to_10("11111",2)<<endl; cout<<from_any_to_10("A1",16)<<endl; cout<<from_any_to_10("a1",16)<<endl; return 0; } Output: $ g++ number_system.cpp && ./a.out 4698 11 31 161 161 Python3 #converts from any number system to decimal number system def from_any_to_10(number,system:int): number=number[::-1].upper()#reversing the string and converting to uppercase p=1 result=0; for c in number:#iterating over the numbers if c <='9' and c>='0': #ord() converts a character to an integer x=ord(c)-48 else: x=ord(c)-55 result+=p*x p*=system return result; if __name__=='__main__': print(from_any_to_10("125a",16)) print(from_any_to_10("1011",2)) print(from_any_to_10("11111",2)) print(from_any_to_10("A1",16)) print(from_any_to_10("a1",16)) OUTPUT : $ python3 number_system.py 4698 11 31 161 161
70,822,301
70,822,473
given list of grades
This is the code I have made, however, what is being displayed is incorrect. Kindly teach me what do I need to fix. #include <iostream> #include <list> using namespace std; bool check(int passing){ int g; if(g<=passing){ return false; }else{ return true; } } int main() { int pg; cout<<"What is the passing grade?"<<endl; cin>>pg; list<int> grades = {100,90,93,95,92,98,97,99,96,94}; grades.remove_if(check); for(int x : grades){ cout<<x<<'\t'; } return 0; }
Use a lambda as a predicate for remove_if like below: #include <iostream> #include <list> int main( ) { std::cout << "What is the passing grade?\n"; int passingGrade { }; std::cin >> passingGrade; std::list<int> grades { 100, 90, 93, 95, 92, 49, 50, 98, 97, 99, 11, 94 }; /*grades.remove_if( [ &passingGrade ]( const int grade ) // lambda approach { return ( grade < passingGrade ) ? true : false; } );*/ for ( auto it = grades.begin( ); it != grades.end( ); ) // for-loop approach { if ( *it < passingGrade ) { it = grades.erase( it ); } else { ++it; } } for ( const int grade : grades ) { std::cout << grade << '\t'; } } Sample I/O What is the passing grade? 50 100 90 93 95 92 50 98 97 99 94 Another sample: What is the passing grade? 95 100 95 98 97 99
70,822,344
70,911,866
Bazel | How to copy resources to build directory?
I am making some openGL project, and want to just copy one of my directory into build directory (I store my textures there). So basically this is what my project structure looks like: |-WORKSPACE |-/src/ | -BUILD | -main.cpp | -*some folders here* |-/resources/ | -BUILD | -*some folders here* All i want is to remain the same relation between directories This is what i tried: # src/BUILD file - I use it to build the whole program cc_binary( name = "OpenGL_Project", srcs = ["main.cpp"], deps = ["//src/renderer:renderer", "//src/scene", "//src/input", "//src/gui"], data = ["//resources:resources"] ) genrule( name = "copy_resources", srcs = ["//resources"], outs = ["resources"], cmd = "cp -r $(SRCS) $(OUTS)" ) And # resources/BUILD file filegroup( name = "resources", srcs = glob(["shaders/**","textures/**"]), visibility = ["//visibility:public"], ) I don't get any errors during build, i tried cleaning it using bazel clean --expunge and building again - but it didn't seem to work. Important to add, there is NO resources folder at build directory at all, not that it's in the wrong place. Do you guys have any ideas what's wrong ?
What you have looks correct, although the copy_resources target isn't necessary. The data dependency on //resources:resources is sufficient for those files to exist in the runfiles directory of //src:OpenGL_Project. The files should exist under bazel-bin/src/OpenGL_Project.runfiles. When you bazel run //src:OpenGL_Project, the files resources/shaders/... and resources/textures/... should be accessible relative to the current directory and relative to the RUNFILES_DIR environment variable. You can also use the C++ runfiles library here to locate the runfiles in more situations, eg if you run the binary directly with ./bazel-bin/src/OpenGL_Project it will also try to find runfiles in argv[0] + ".runfiles".
70,822,373
70,822,543
How can I access that array of indexes in C++?
#include<bits/stdc++.h> using namespace std; int arr[10][2]; int main(){ memset(arr,-1,sizeof(arr)); for(int i=0;i<10;i++) cout<<arr[i][i]<<" "; return 0; } result = -1 -1 -1 -1 -1 -1 -1 0 0 0 I declared an array of size 2 * 10 as a global variable and initialized it to -1 using the memset function. However, how did this result come out when I approached the index like arr[i][i] while using the for statement? Question. How can there be values of arr[3][3], arr[4][4]... that are not declared? Why are the values of arr[7][7], arr[8][8], arr[9][9] different from the previous values? Thank you.
Your program has undefined behavior because you're accessing elements outside the bounds of the array arr. When you wrote: int arr[10][2]; //arr is a 2D array The above statement defines a 2D array. This means, arr has 10 elements and each of those 10 elements are themselves an array of 2 int elements. This also means that you can only access(safely) the elements: arr[0][0] arr[0][1] arr[1][0] arr[1][1] arr[2][0] arr[2][1] ... ... arr[9][0] arr[9][1] And if you try to(which you do in your program inside for loop) access any other elements outside the above bounds, you'll get 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(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. Solution 1 One alternative is to use std::vector as shown below: //create a 2D vector with 10 rows and 2 columns where each int element has value -1 std::vector<std::vector<int>> arr(10, std::vector<int>(2, -1)); Solution 2 You should consider using std::fill instead of memset: std::fill(*arr, *arr + 10*2, -1); 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,822,603
70,822,636
Using Destructor in inheritance
In this inheritance program I create 2 classes which A is parent and B is child class . and i crate cons of both classes and also use Destructor, and both classes have tow objects . @ MY question is that when my program is run then its output show 2 Destructor of class a why ? #include <iostream> using namespace std; class A { int a; public: A(int a1) // cons(A) { a = a1; } A() {} // Dis(A) ~A() { cout << "A Disturctor"<< endl; } }; class B : public A // inheritance { int b; public: B(int b1) // cons (A) { b = b1; } ~B() { cout << "B Disturctor" << endl; } // Dis(B) }; int main() { A hamza(1); B Ramza(4); return 0; } Output: B Disturctor A Disturctor1 A Disturctor2
The first "A Disturctor" is for object "A hamza(1)". The second "A Disturctor" is for object "B Ramza(4)" Since B inherits from A, when object of class B is destroyed, destructor of both class B and class A are called.
70,822,670
70,823,269
How to send messages properly from python server to c++ client?
I have a python server running on the following code: import socket ss=socket.socket(socket.AF_INET,socket.SOCK_STREAM) ss.bind(('0.0.0.0',8080)) ss.listen(5) cs,adr=ss.accept() print("Got a connection from:"+str(adr)) while 1: msg=input('Enter your message:') cs.send(msg.encode('ascii')) cs.close() For client I'm using C++. client.h: #include<WinSock2.h> #include<WS2tcpip.h> #include<iostream> #pragma comment(lib,"ws2_32.lib") #pragma warning(disable:4996) class client { private: const char* IP; int PORT; SOCKET sock; public: client(char* ip, int port){ IP = ip; PORT = port; } void createSession();//Creates socket and connects with the server. void sendData(char* message);//Sends message to the server, it works fine char* receive() { char message[2000]; if (recv(sock, message, 2000, 0) == SOCKET_ERROR) { WSACleanup(); return (char*)"Failed to receive Message"; } return message; } }; client.cpp: #include"client.h" #include<iostream> #define IP "127.0.0.1" #define port 8080 using namespace std; int main() { client c1((char*)IP, port); c1.createSession(); while (1) { char* message; message = c1.receive(); cout << IP << ':' << port << " Says: " << message << endl; } return 0; } but the message that I'm receiving is garbage. I'm guessing it's a conversion error because for python clients, I'd use recv(length).decode('ascii') to decode the message first when receiving. How do I fix this?
char* receive() { char message[2000]; if (recv(sock, message, 2000, 0) == SOCKET_ERROR) { WSACleanup(); return (char*)"Failed to receive Message"; } return message; } ... message = c1.receive(); cout << IP << ':' << port << " Says: " << message << endl; This is wrong in multiple places: You are reading the data into a buffer allocated on the function stack (message[2000]). This buffer will be automatically freed after the functions exits, so what you return from the function is no longer there. When printing you treat the message as a \0-terminated char[] even though its not \0 terminated. This means that garbage after the received message will be printed though, until a \0 gets found. It might well be that no \0 gets found within the buffer in which case it will continue to read, possibly outside allocated memory and thus crash. You assume that the send in Python will send the full message but this is not guaranteed. Check the return value of send on how much was actually send or use sendall. You assume that recv in C will receive the full message but this is not guaranteed. TCP has no concept of a message and recv will return just return the bytes already received. Especially with large messages or small TCP windows this might not be the complete message you intended.
70,822,701
70,822,850
QT6 - signal/slot between 2 classes
I have created a new class for qpushbutton, I am trying to establish signal slot communication between this class and my mainwindow class connect(&MyPushButton, &pushbutton::pb_isChecked, this, &MainWindow::MainWindowPBClicked, Qt::DirectConnection); I used this code but as output only qDebug("pushButtonClicked"); I can get this output. After that, the slot I called with "emit" does not work. void pushbutton::pushButtonClicked() { if (isChecked()) { qDebug("pushButtonClicked"); **emit pb_isChecked();** } } all code in my project; main.cpp #include "mainwindow.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication app(argc, argv); MainWindow ui; ui.show(); return app.exec(); } mainwindow.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QDebug> #include "pushbutton.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); public slots: void MainWindowPBClicked(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H mainwindow.cpp #include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); pushbutton MyPushButton; connect(&MyPushButton, &pushbutton::pb_isChecked, this, &MainWindow::MainWindowPBClicked, Qt::DirectConnection); } MainWindow::~MainWindow() { delete ui; } void MainWindow::MainWindowPBClicked() { qDebug("MainWindowPBClicked"); } pushbutton.h #ifndef PUSHBUTTON_H #define PUSHBUTTON_H #include <QWidget> #include <QPushButton> class pushbutton : public QPushButton { Q_OBJECT public: explicit pushbutton(QWidget *parent = nullptr); public slots: void pushButtonClicked(); signals: void pb_isChecked(); }; #endif // PUSHBUTTON_H pushbutton.cpp #include "pushbutton.h" #include "mainwindow.h" pushbutton::pushbutton(QWidget *parent) : QPushButton{parent} { setAcceptDrops(true); connect(this, &QPushButton::clicked, [this]() { pushButtonClicked(); }); } void pushbutton::pushButtonClicked() { if (isChecked()) { qDebug("pushButtonClicked"); emit pb_isChecked(); } }
CASE 1: Not creating button in UI file: In your class MainWindow, variable MyPushButton is a local variable that gets destroyed after it end its scope in constructor. You need to create a dynamic variable of pushButton like this: pushbutton *MyPushButton = new pushButton(this); connect(MyPushButton, SIGNAL(pb_isChecked()), this, SLOT(MainWindowPBClicked()), Qt::DirectConnection); CASE 2: Creating button in UI file: In this case you cannot use your custom signal pb_isChecked(). You will need to use standard QPushButton signal such as clicked() connect(ui->MyPushButton, SIGNAL(clicked()), this, SLOT(MainWindowPBClicked()), Qt::DirectConnection);
70,823,564
70,823,595
what will bw the output of this code? c++
#include <iostream> using namespace std; int f(int i){ int k=0; if(i>0) { int k=i*10; } else { int k= i++; } cout <<k; return i; } int main() { cout << f(1); cout << "."; cout << f(0); return 0; } This is the code, compiler shows "01.01" which i quite don't understand, any help will be very much welcomed!
int k = i * 10; and int k = i++; are declarations of k that shadow the outer k. The statement std::cout << k; in the outer scope therefore always outputs zero. The only effect of the if body is to increase i by 1. And it only does that if i is zero (or less). That value of i is returned printed. Thus the output is 01.01. Armed with a line by line debugger, the shadowing effect will be obvious.
70,823,604
70,937,048
Showing metadata on response side with GRPC on BloomRPC
My goal is sending source part from request to response side. In bloomRPC, with these codes, I can send name and uuid to response side, but I cannot send metadata. Is there a similar code that I can go for metadata in here? If you need editor and response in bloomRPC, I can send that too. //main.cpp: class RouteGuideImpl final: public project::EventServer::Service{ public: grpc::Status PubEvent(grpc::ServerContext *context, const events::PubEventRequest *request, events::PubEventResponse *response){ std::cout<<"Welcome"<<std::endl; for(int i=0;i<request->eventsize();i++){ auto value= response->add.subs(); value->set_name(request->events(i).source().name()); value->set_uuid(request->events(i).source().uuid()); } return grpc::Status::OK; } }; //.proto file: message Source{ string name = 1; string uuid = 2; map<string,string> metadata = 3; }
Well, metadata is a google map object. So I did this and it worked: for(const auto& elements_source_metadata : request->events(i).source().metadata()){ x->mutable_metadata()->insert({elements_source_metadata.first, elements_source_metadata.second});
70,823,631
70,833,077
get remaining data size on tcp socket on mingw
I want to get size of remaining data on tcp socket. On linux I can do this: #include <sys/ioctl.h> int count; ioctl(sockfd, FIONREAD, &count); But this does not work with mingw, is there any alternative solution that works in mingw?
I found the solution: #include <winsock2.h> unsigned long count; ioctlsocket(sockfd, FIONREAD, &count);
70,823,702
70,823,926
Why is a local automatic object from a try block still alive in the catch block when I throw that object by address?
Here is the code: #include <iostream> using namespace std; class A { public: void print() { cout << "Object is still alive" << endl; } }; int main() { try { A a1 = A(); A* a = &a1; throw a; } catch (A* a) { a->print(); } } Why is object a1 still alive in the catch block (you can check it for yourself, print method works) even though I have thrown exception of type pointer to an object of class A? I thought that all local objects in the try block get destroyed as soon as we leave it?
Why is object a1 still alive in the catch block It's no longer alive. you can check it for yourself, print method works That proves nothing about the lifetime of the object. I thought that all local objects in the try block get destroyed as soon as we leave it? You have been thinking correctly. The behaviour of the program is undefined. I expected my program to crash This is where you made the biggest mistake. The program is not guaranteed to crash when the behaviour is undefined. You cannot rely on such assumption.
70,823,791
70,823,880
how to delete a member of vector which is a member of class
I am writing a program which is a system of library. I have made a class of books which has setter and getter for setting and getting each information of a book; such as the name of book and the name of author. then I made a vector of my class. for example vector <books> book(1000). for instance for book[1] the name is abcd and the name of author is efg now I need to declare a function which can delete a member of vector , for example delete book[1]. but I dont know how to do it. I will be appreciate If anyone can help me! class books { public: books() { } void set_name(string input) { name = input; } void set_author_name(string input) { author_name = input; } string get_name() { return name; } string get_author_name() { return author_name; } private: string name, author_name; }; vector<books> book(1000);
std::vector::erase is here for you! It accepts an iterator to the element to be deleted, so something like book.erase(book.begin() + idx); would work to delete the element at index idx (in O(N) time)
70,824,256
70,824,442
Why should I explicitly pass typename to std::forward?
Why is it necessary to explicitly indicate the type of template argument in std::forward? template <class T> void foo (T&& x) { goo (x); // always an lvalue goo (std::forward<T>(x)); // rvalue if argument is rvalue } considering std::forward implementation: template <typename T> T&& forward(std::remove_reference_t<T>& x) { return static_cast<T&&>(x); } and std::remove_reference implementation: template< class T > struct remove_reference {typedef T type;}; template< class T > struct remove_reference<T&> {typedef T type;}; template< class T > using remove_reference_t = typename remove_reference<T>::type;
The argument's type in std::forward() is: remove_reference<T>::type Here T position is left of the scope resolution operator ::, which makes it a "non-deduced context" (see non-deduced context on cppreference). Because it is not automatically deduced, you have to provide the type yourself.
70,825,012
70,826,004
Function to round a float to nearest float with specific allowed decimals
I'm trying to write a function that behaves like the following (c++, but answers in any language accepted) float roundToGivenDecimals(float input, float allowedDecimals[]) usage: float roundToGivenDecimals(10.4, [0.1, 0.45, 0.67, 0.80, 0.99]) // output: 10.45 float roundToGivenDecimals(3.15, [0.1, 0.45, 0.67, 0.80, 0.99]) // output: 3.15 float roundToGivenDecimals(3.01, [0.1, 0.45, 0.67, 0.80, 0.99]) // output: 2.99 Similar to a standard round() method, but with only specific fractional values allowed I've been thinking this over for a while but I'm struggling to come up with a nice solution, any ideas would be greatly appreciated!
@Daniel Davies, I changed a bit your answer, now it works correctly: double roundToGivenDecimals(double input, double allowedDecimals[], int numAllowedDecimals) { double inputFractional = input - floor(input); double result = input; double minDiff = 1; for (int i = 0; i < numAllowedDecimals; ++i) { if (fabs(inputFractional - allowedDecimals[i]) < minDiff) { result = floor(input) + allowedDecimals[i]; } else if (fabs(inputFractional + 1 - allowedDecimals[i]) < minDiff) { result = floor(input) - 1 + allowedDecimals[i]; } minDiff = fabs(input - result); } return result; }
70,825,368
70,826,132
How do I correctly bind keys using the command pattern?
I've been working on a game using c++ and sfml and I've been trying to implement the command pattern as seen in the link below: https://gameprogrammingpatterns.com/command.html. More specifically, I am trying to implement the command pattern so that it can be used for any character in the scene. I've set up a general command class: class Command { public: ~Command(); virtual void execute(Character& character) = 0; }; And then a bunch of classes that inherit from this class, for example: #include "Command.h" class WalkDownCommand : public Command { public: virtual void execute(Character& character) override { character.walkDown(); } }; Then I created a character class that contains all the functions for walking, and a shape to represent it's body: #include <SFML\Graphics.hpp> class Character { public: Character(); ~Character(); void draw(sf::RenderWindow* renderWindow); void walkRight(); void walkLeft(); void walkUp(); void walkDown(); private: sf::CircleShape* tempShape; }; These functions are then called using their respective command Class. I've also created a HandleInput function that checks whether a key is pressed and returns a reference to a specific command object: #include "Command.h" class InputHandler { public: Command* handleInput(); private: Command* W_KEY; Command* A_KEY; Command* S_KEY; Command* D_KEY; }; The handleInput function looks as follows: Command* InputHandler::handleInput() { if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { std::cout << "W key is pressed" << std::endl; return W_KEY; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { std::cout << " A key is pressed" << std::endl; return A_KEY; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { std::cout << "S key is pressed" << std::endl; return S_KEY; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { std::cout << "D key is pressed" << std::endl; return D_KEY; } return NULL; } In the games main loop, I created a Command pointer object that calls the handleInput function to check for input. If it finds a command, it executes this command ('gloon' is the object of type Character): Command* command = inputHandler.handleInput(); if (command) { command->execute(gloon); } When running this, the handleInput function gets correctly called and then returns one of the pressed keys. However, the program crashes right after, stating: Exception thrown: read access violation. command was 0xFFFFFFFFFFFFFFFF. In the link I showed of the beginning of the page, the command pattern description also states that I need to bind the Command* objects to the correct function. This might be what is causing the issue, but I'm having trouble to understand how to do this. Any help is appreciated!
Maybe, try something like this (to initialize pointers in your class InputHandler): #include "Command.h" class InputHandler { public: InputHandler() { W_KEY = new WalkUpCommand; A_KEY = new WalkLeftCommand; D_KEY = new WalkRightCommand; S_KEY = new WalkDownCommand; } ~InputHandler() { delete W_KEY; delete A_KEY; delete S_KEY; delete D_KEY; } Command* handleInput(); private: Command* W_KEY; Command* A_KEY; Command* S_KEY; Command* D_KEY; }; I'm not sure, but hope it will be helpful
70,825,617
70,825,677
Fill a double pointer matrix from CSV file
I want to fill a double pointer 2D array with the values from a CSV. I don't want to read the csv file to get the size of the array before filling it and I want to do it with pointers and not std::vector. My current code is this std::pair<int, int> readFile(const std::string &filename, int **matrix) { std::fstream file{filename, std::ios::in}; if (file.is_open()) { std::string line{}; int col{0}; int row{0}; while (std::getline(file, line)) { // Check how many cols there are int len = std::count(begin(line), end(line), ',') + 1; // Allocate a vector with size the cols found before int *tmp = reinterpret_cast<int *>(calloc(len, sizeof(int))); col = 0; // Fill the temp vector with the read numbers while (line.size() > 0) { int num{-1}; // This is just to parse a number, nothing special here if (line.find(",") != std::string::npos) { num = std::stoi(line.substr(0, line.find(","))); line.erase(0, line.find(",") + 1); // +1 to also delete delimiter } else { num = std::stoi(line); line = ""; // Set line empty to go out of the while } tmp[col] = num; col++; } // Assign the temporal vector to a row of the matrix matrix[row] = tmp; row++; } return {row, col}; } std::cout << "Failed to open file at " << filename << std::endl; return {-1, -1}; } int main() { int **matrix; auto shape = readFile("file.csv", matrix); for (size_t row = 0; row < shape.first; row++) { for (size_t col = 0; col < shape.second; col++) { std::cout << matrix[row][col] << " "; } std::cout << std::endl; } // Free the pointers for (size_t row = 0; row < shape.first; row++) { free(matrix[row]); } } My current result is: 0 0 -751362032 21853 1 2 3 4 2 3 2 1 3 4 5 3 2 1 4 3 2 2 2 2 2 free(): double free detected in tcache 2 Aborted (core dumped) It seems that the fist tmp vector is being freed before the print (the rest of the values are right). Any idea what I'm missing?
You're passing matrix to your readFile function uninitialized, and then go on and access it with matrix[i]=tmp. That can cause all kinds of issues since you're working with memory that doesn't belong to you.
70,825,761
70,825,887
Leaky bucket algorithm with concurrency
Trying to mimic a scenario where multiple threads are creating the traffic to fill the buckets & a thread which leaks the bucket a specified rate. However,code is running into deadlock. Could you pl review this code ? Let me know if you see any errors & best possible modifications that I should add. Code #include <iostream> #include <mutex> #include <condition_variable> #include <thread> #include <atomic> #include <chrono> using namespace std; class LeakyBucket { public: LeakyBucket(int size, int rate) : maxCapacity(size), leakRate(rate), filled(0) {} void add(int newDataSize) { unique_lock<mutex> lk(_mtx); _cond.wait(lk, [this](){ return filled<=maxCapacity; }); filled = (filled+newDataSize) > maxCapacity ? maxCapacity:(filled+newDataSize); cout<<"\n Filled bucket with : "<<newDataSize; cout<<"\n Filled: "<<filled<<"\n ----------"; _cond.notify_one(); } void leak() { while(1) { { unique_lock<mutex> lk(_mtx); _cond.wait(lk, [this]() { return filled > 0 || _done; }); if(_done) break; filled = (filled-leakRate<0) ? 0 : (filled-leakRate); cout << "\n Leaked bucket with leakRate"; cout << "\n BucketFilledRemain: " << filled << "\n ----------"; _cond.notify_one(); } _sleep: this_thread::sleep_for(chrono::seconds(1)); } } bool _done = false; private: atomic<int> filled; int maxCapacity; int leakRate; // Per second mutex _mtx; condition_variable _cond; }; void runLeakyBucketAlgorithm() { LeakyBucket *lb = new LeakyBucket(30, 20); thread t1(&LeakyBucket::leak, lb); thread t2([&](){ for(int i=0; i<10; i++) { cout<<"\n launching thread: "<<i; lb->add(rand()%40); } this_thread::sleep_for(chrono::seconds(5)); lb->_done = true; }); if(t2.joinable()) { t2.join(); } t1.join(); } O/p: launching thread: 0 Filled bucket with : 7 Filled: 7 ---------- launching thread: 1 Filled bucket with : 9 Filled: 16 ---------- launching thread: 2 Leaked bucket with leakRate BucketFilledRemain: 0 ---------- Filled bucket with : 33 Filled: 30 ---------- launching thread: 3 Filled bucket with : 18 Filled: 30 ---------- launching thread: 4 Filled bucket with : 10 Filled: 30 ---------- launching thread: 5 Filled bucket with : 32 Filled: 30 ---------- launching thread: 6 Filled bucket with : 24 Filled: 30 ---------- launching thread: 7 Filled bucket with : 38 Filled: 30 ---------- launching thread: 8 Filled bucket with : 3 Filled: 30 ---------- launching thread: 9 Filled bucket with : 29 Filled: 30 ---------- Leaked bucket with leakRate BucketFilledRemain: 10 ---------- Leaked bucket with leakRate BucketFilledRemain: 0
There are multiple fundamental bugs in the shown code. thread t1(&LeakyBucket::leak, lb); leak() will wait until the bucket has at least 0 fill rate, then subtract the leak rate from it. Then it will be done. That's it. It will be no more. The leaking thread will cease to exist. It will become an ex-thread. It will be pining for the fjords, forever. Once the bucket has leaked once, its leaking hole gets plugged, and it becomes a completely leak-proof bucket. new LeakyBucket(30, 20); The bucket's capacity is 30, and it's leak rate is 20. lb->add(rand()%40); This gets called ten times, to add anywhere between 0 and 39 drops of water. So, let's say the first time we drop 20 drops of water into the bucket. The leak thread will wake up, take those 20 drops of water out, and earn its well-deserved retirement. But wait, we have nine more additions of water coming! The second call to add() will drop 25 drops of water. The third attempt adds 30 drops of water. The bucket is now over capacity. The fourth call to add() will now block forever because, as we've just seen, the bucket is completely leak-proof now. That's the first bug: the bucket leaks once, then it does not leak any more. _cond.wait(lk, [this]() { return filled > 0; }); filled -= leakRate; The leak in the bucket will wait until there's at least 1 drop of water in the bucket, then leak 20 drops of water. So, if five drops of water were already in the bucket the bucket will, after all of this, have a negative fifteen drops of water. This obviously makes no sense, so this would be the second bug that will need to get fixed, before this works correctly. There's probably a third bug here, too. The bucket is defined as having a certain capacity. However, in one of my examples, above, the bucket ends up having more drops of water than its stated capacity. That also does not add up, as well.
70,825,787
70,825,937
How does `std::osyncstream` manage the out stream?
I wonder how a std::osyncstream object prevents data race conditons? Does it lock some mutex? I'm specifically talking about the below program: #include <iostream> #include <fstream> #include <thread> #include <syncstream> void worker( const std::size_t startValue, const std::size_t stopValue, std::ostream& os ) { for ( auto idx { startValue }; idx < stopValue; ++idx ) { std::osyncstream out { os }; out << "thread: " << std::this_thread::get_id( ) << "; work: " << idx << '\n'; } } void runThreads( std::ostream& os ) { std::jthread t1 { worker, 10000, 20000, std::ref( os ) }; std::jthread t2 { worker, 20000, 30000, std::ref( os ) }; } int main( ) { std::ofstream file { "out.txt" }; runThreads( file ); } The source of the above code can be viewed here. Although I have made slight modifications to make it better and safer. This simple program prints 20,000 lines into a file without generating a messy output. The possible output: thread: 2; work: 10000 thread: 3; work: 20000 thread: 2; work: 10001 thread: 2; work: 10002 thread: 2; work: 10003 thread: 2; work: 10004 thread: 2; work: 10005 thread: 2; work: 10006 . . . What's going on behind the scenes? How do these two threads communicate with each other? Do they have separate copies of syncstream object? How does this object (i.e. out) manage the output stream os?
Does it lock some mutex? Yes, indirectly. The std::basic_osyncstream class, of which osyncstream is a specialization of the form basic_osyncstream<char>, is derived from std::basic_ostream and will typically have just one 'extra' member, of the std::basic_syncbuf class. From cppreference: Typical implementation of std::basic_osyncstream holds only one member: the wrapped std::basic_syncbuf. It is that basic_syncbuf object that implements the output synchronization, preventing data races. Again, from cppreference (bolding mine): Typical implementation of std::basic_syncbuf holds a pointer to the wrapped std::basic_streambuf, a boolean flag indicating whether the buffer will transmit its contents to the wrapped buffer on sync (flush), a boolean flag indicating a pending flush when the policy is to not emit on sync, an internal buffer that uses Allocator (such as std::string), and a pointer to a mutex used to synchronize emit between multiple threads accessing the same wrapped stream buffer (these mutexes may be in a hash map with pointers to basic_streambuf objects used as keys).
70,826,115
70,932,588
Using regular pointers on Polymorphism c++
I'm trying to learn Polymorphism in C++, and the way I've been learning it was with raw pointers or smart pointers but then I've been trying to use regular pointers this time and I even tried to add the pointers to a vector from the constructor like this: std::vector<bank_account*> bank_accounts; bank_account::bank_account(std::string Name, int Balance) : name{Name}, password{create_random_passowrd()}, balance{Balance}, Id{create_ID()} {} saving_account::saving_account(std::string Name, int Balance, float Interest) : bank_account{Name, Balance}, interest_rate{Interest}{ bank_account *ptr = this; bank_accounts.push_back(ptr); } I did things this way because I would like to avoid doing "push.back" to add every object I create when calling the constructor(every attempt I did with smart pointers or raw pointers I always ended up calling the same constructor again and then creating an infinite loop) and also to achieve polymorphism without worrying about memory leaks in this situation, but I'm finding myself with some issues on using virtual functions and I think it might have something to do with this. I'd be really glad if you guys could tell if this is a good idea or not and also I'd like to say thanks for your attention!
To your last comment, yes, those are two examples of different concerns. The main issue with this approach is that pointers are being put together in a vector, regardless of where actual account objects are constructed within the program, which may be entirely unrelated cases. Therefore, the principle of separation of concerns implies that a bank account class should just model the relevant aspects of some type of bank account. If, for example, it will be used to represent a list of bank accounts associated with a client of a bank, then it should be the responsibility of a "client" object to manage that list. Now, I'm not sure what issues you encountered with smart pointers, but since I would recommend using them in the example I just gave, here is a snippet showing the correct usage: #include "bank_account.h" #include <memory> #include <vector> class Client { using account_ptr = std::unique_ptr<bank_account>; std::vector<account_ptr> m_accounts; // ... }; Different account types can be added with std::make_unique, available since C++14: m_accounts.emplace_back(std::make_unique<bank_account>("A", 100)); m_accounts.emplace_back(std::make_unique<savings_account>("B", 2000, 0.5));
70,826,250
70,826,290
Simplification of appender function using std::accumulate
I wanted a simple function that takes a collection of strings and appends them and returns one string which is each string item appended together. I thought std::accumulate was the way to go but interested to hear if this code could be improved. Is there a simpler append type function that can be used here instead of the lambda? Is this overly complicated and best achieved by some other code? #include <string> #include <vector> #include <iostream> #include <numeric> std::string concatenate(std::vector<std::string> strings) { return std::accumulate(strings.begin(), strings.end(), std::string(""), [](std::string s1, std::string s2) { return s1 + s2; }); } int main() { std::vector<std::string> vec2{ "aaa","bbb","ccc","ddd","eee","fff" }; std::cout << concatenate(vec2) << std::endl; }
Yes, you can omit the lambda entirely (or use std::plus<>{}). Also the "" can be removed from std::string(""), or the whole third argument can be removed if you switch to std::reduce: std::reduce(strings.begin(), strings.end()); Also concatenate should take the vector by a const reference, or even better a std::span<const std::string> (by value). Also libfmt can be used for this: fmt::format("{}", fmt::join(strings, ""));
70,826,720
70,828,373
Problem with writing a value using CIN to individual data in a struct C++
Okay so here is what I want to do, My overall goal is to create a sniping bot to snipe (The term used is) "OG Usernames" I'm currently using a struct within a header file, The reason for me doing this is to reduce code duplication to make the program run more efficiently. My overall goal is to pull a timestamp from a web page and calculate the exact time in milliseconds to run a task. Within the header file it has this: struct TimeTilNameDrop { int days; //Integer for days int hours; //Integer for hours int minutes; //Integer for minutes int seconds; //Integer for seconds int miliseconds; //Integer for miliseconds }; I'm trying to get the user's input in days, hours, minutes, seconds and ill get it to calculate the milliseconds, I appreciate this won't be accurate as the time of the program to run the task will take a few milliseconds to I need to factor that in. #pragma warning(disable : 4996) #include <iostream> #include <ctime> #include <time.h> #include <NameDropData.h> //The headerfile containing the struct using namespace std; //Linker Decleration. struct TimeTilNameDrop; void Test(TimeTilNameDrop); int TurboSnipe(Test) { cout << "Please enter the days til name drop"; cin >> days; cout << "Please enter the hours til name drop"; cin >> hours; cout << "Please enter the minutes til name drop"; cin >> minutes; cout << "Please enter the seconds til name drop"; cin >> seconds; } I've tried looking at other tutorials with the struct being housed in a headerfile, I know it probably would have worked in its local class. However, I like the idea of efficiency. Any help would be appreciated. P.S I am a noob and this is my first project. I understand that it may not work or I may not have the capabilities for it but I thought it would be a good project to deal with. Oh and if anyone has any advice on any good video courses for C++ suggestions are welcome, I've currently been doing "The Cherno's" C++ series and I've just learned how pointers work. Suggestions are welcome :)
I assume you are trying to get information to be stored into a struct based on your description. The main issue I noticed with what you are currently doing is that you never create an instance of the struct. You need to create an instance of the struct to store information in it. Here is an example of how that could be done: //header file where stuct is #include "stackOverflow.h" //linker declaration for struct struct TimeTilNameDrop; using namespace std; int main() { //create an instance of the stuct named timeStruct TimeTilNameDrop timeStruct; cout << "Please enter the days til name drop"<<endl; cin >> timeStruct.days; cout << "Please enter the hours til name drop"<<endl; cin >> timeStruct.hours; cout << "Please enter the minutes til name drop"<<endl; cin >> timeStruct.minutes; cout << "Please enter the seconds til name drop"<<endl; cin >> timeStruct.seconds; return 0; }
70,827,289
70,827,328
Inheritance with template classes
I'm trying to figure out, how can I inherit from template class to template class. The problem is: I can't use protected members of Parent class. Example: template <class N> class Parent { protected: N member; public: Parent(N aa){ member = aa; } }; class Child1: public Parent<int>{ public: Child1(int a): Parent<int>(a) { member += 1; // works } }; template<class Q> class Child2: public Parent<Q>{ public: Child2(int a): Parent<Q>(a) { member += 1; // does not work (use of undeclared identifier) } }; How can I use "member" in the Child2 class? Thanks for your time
You need to use this->member or Parent<Q>::member. In the second case, member is a "dependent name" because the existence of member from the base class template Parent<Q> depends on the type of class Q in the template, whereas in the first example there is no dependent type, the compiler can statically analyze that Parent<int> contains member.
70,827,356
70,827,442
Why is this `my::test` not deduced template parameter?
I had a problem similar to this one: std::function and std::bind: how to load a std::bind with a function template I didn't find any satisfactory answer, but my doubt is similar (not the same) as this post above The code: #include <iostream> #include <functional> using namespace std; namespace my { template <typename T> struct test; template <typename R, typename ...Ts> struct test<R(Ts...)>{ test(R(*func)(Ts...)){ //None content, only test } }; } void install1(my::test<int(int, int)> func) { } template <typename R, typename ...Ts> void install2(my::test<R(Ts...)> func) { } int add(int a, int b) { return a + b; } int main(int argc, char *argv[]) { install1(add); my::test<int(int, int)> fun = add; install1(fun); install2<int, int, int>(add); return 0; } Problems I've noticed: When calling the install 2 function, the parameters cannot be deducted If I use in void install2 this code template <typename R, typename A, typename B> void install2(my::test<R(A, B)> func) {} install2<int, int, int>(add); This code above works fine, but if i remove "A, B" and put "...Ts" the program doesn't compile Thank in advance, and I apologize for any misunderstanding in the description of the problem (I'm using google translate)
With template <typename R, typename ...Ts> void install2(my::test<R(Ts...)> func) and calling install2<int, int, int>(add); you have provided explicit template arguments for the first template parameter and two elements of the parameter pack. But there could still be more elements in the pack. Therefore the function parameter still has a type containing template parameters that need to be deduced (basically my::test<int(int, int, Ts...)>). So template argument deduction will be applied to the argument/parameter pair and it will fail, because the function argument you are providing does not have a my::test type. With template <typename R, typename A, typename B> void install2(const char name[], my::test<R(A, B)> func) you have provided template arguments to all template parameters explicitly, so my::test<R(A, B)> func will not be a deduced context anymore. As mentioned in the comments to the question install2<int, int, int>({add}); also works because the braces make the function argument/parameter pair a non-deduced context. If you want to be able to call the function with explicit template arguments and without braces, you can make the function parameter always a non-deduced context, for example using C++20's std::type_identity: template <typename R, typename ...Ts> void install2(std::type_identity_t<my::test<R(Ts...)>> func) However, then it is not possible anymore to call it without an explicit template argument list. You could use both this version and the original as overloads, forwarding one to the other, to cover all situations you mention in your example code.
70,827,395
70,827,509
Why memoization works, but returns false value from unordered_map
The following program countConstruct should return the number of possible way the target string can be constructed from the given wordBank. Now, the memo object seem to store the correct value for "ab" which is 2, but it prints out 1. I just cannot figure out, what am I keep missing here over and over again. I appreciate anyone who can enlighten me about my failiure. Thank you. #include <string> #include <unordered_map> #include <iostream> #include <vector> using namespace std; unordered_map<string, int> memo; bool countConstruct(const string& target, const vector<string>& wordBank) { if (target.size() == 0) { return 1; } if (memo.find(target) != memo.end()) { return memo[target]; } int totalCount = 0; for (int i = 0; i < wordBank.size(); ++i) { if (wordBank[i].size() <= target.size()) { string prefix = target.substr(0, wordBank[i].size()); if (prefix == wordBank[i]) { totalCount = totalCount + countConstruct(target.substr(wordBank[i].size()), wordBank); } } } return memo[target] = totalCount; } int main() { // int c = countConstruct("purple", vector<string>({"purp", "p", "ur", "le", "purpl"})); // int d = memo["purple"]; // memo.clear(); // cout << "countConstruct(purple, {purp, p, ur, le, purpl}) = " << countConstruct("purple", vector<string>({"purp", "p", "ur", "le", "purpl"})) << '\n'; // memo.clear(); // cout << "countConstruct(abcdef, {ab, abc, cd, def, abcd}) = " << countConstruct("abcdef", vector<string>({"ab", "abc", "cd", "def", "abcd"})) << '\n'; // memo.clear(); // cout << "countConstruct(skateboard, {bo, rd, ate, t, ska, sk, boar}) = " << countConstruct("skateboard", vector<string>({"bo", "rd", "ate", "t", "ska", "sk", "boar"})) << '\n'; // memo.clear(); // cout << "countConstruct(enterapotentpot, {a, p, ent, enter, ot, o, t}) = " << countConstruct("enterapotentpot", vector<string>({"a", "p", "ent", "enter", "ot", "o", "t"})) << '\n'; // memo.clear(); // cout << "countConstruct(eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef, {e, ee, eee, eeee, eeeee, eeeeee}) = " << countConstruct("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef", vector<string>({"e", "ee", "eee", "eeee", "eeeee", "eeeeee"})) << '\n'; // memo.clear(); cout << "countConstruct(ab, {ab, a, b}) = " << std::flush << countConstruct("ab", vector<string>({"ab", "a", "b"})) << "\n"; cout.flush(); memo.clear(); return 0; }
Please change bool --> int Now it outputs: countConstruct(ab, {ab, a, b}) = 2 Final code: #include <string> #include <unordered_map> #include <iostream> #include <vector> using namespace std; unordered_map<string, int> memo; int countConstruct(const string& target, const vector<string>& wordBank) { if (target.size() == 0) { return 1; } if (memo.find(target) != memo.end()) { return memo[target]; } int totalCount = 0; for (int i = 0; i < wordBank.size(); ++i) { if (wordBank[i].size() <= target.size()) { string prefix = target.substr(0, wordBank[i].size()); if (prefix == wordBank[i]) { totalCount = totalCount + countConstruct(target.substr(wordBank[i].size()), wordBank); } } } return memo[target] = totalCount; } int main() { // int c = countConstruct("purple", vector<string>({"purp", "p", "ur", "le", "purpl"})); // int d = memo["purple"]; // memo.clear(); // cout << "countConstruct(purple, {purp, p, ur, le, purpl}) = " << countConstruct("purple", vector<string>({"purp", "p", "ur", "le", "purpl"})) << '\n'; // memo.clear(); // cout << "countConstruct(abcdef, {ab, abc, cd, def, abcd}) = " << countConstruct("abcdef", vector<string>({"ab", "abc", "cd", "def", "abcd"})) << '\n'; // memo.clear(); // cout << "countConstruct(skateboard, {bo, rd, ate, t, ska, sk, boar}) = " << countConstruct("skateboard", vector<string>({"bo", "rd", "ate", "t", "ska", "sk", "boar"})) << '\n'; // memo.clear(); // cout << "countConstruct(enterapotentpot, {a, p, ent, enter, ot, o, t}) = " << countConstruct("enterapotentpot", vector<string>({"a", "p", "ent", "enter", "ot", "o", "t"})) << '\n'; // memo.clear(); // cout << "countConstruct(eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef, {e, ee, eee, eeee, eeeee, eeeeee}) = " << countConstruct("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef", vector<string>({"e", "ee", "eee", "eeee", "eeeee", "eeeeee"})) << '\n'; // memo.clear(); cout << "countConstruct(ab, {ab, a, b}) = " << std::flush << countConstruct("ab", vector<string>({"ab", "a", "b"})) << "\n"; cout.flush(); memo.clear(); return 0; }
70,827,531
70,827,571
Aliasing a nested class of a template
I have the following in a header file: template <typename T> class RingDeque { ... struct Iterator { using reference = T&; reference operator*() const; } } and I want to implement the operator*() function in the cpp file. I currently have the following in the cpp file: template <typename T> typename RingDeque<T>::Iterator::reference RingDeque<T>::Iterator::operator*() const { ... some implementation } Is there anyway I can alias a type to RingDeque<T>::Iterator? Perhaps something like this? template <typename T> using MyIterator = RingDeque<T>::Iterator; template <typename T> MyIterator::reference MyIterator::operator*() const { ... some implementation } I've tried many variations on this, and I haven't been able to substitute the types in the implementation of the method. For example, with the following code: template <typename T> using MyIterator = typename RingDeque<T>::Iterator; template <typename T> RingDeque<T>::Iterator::reference MyIterator::operator*() const { return this->_data[0]; } I get the following error message: ringDeque.cpp:49:1: error: missing 'typename' prior to dependent type name 'RingDeque<T>::Iterator::reference' RingDeque<T>::Iterator::reference MyIterator::operator*() const { ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ typename ringDeque.cpp:49:35: error: 'MyIterator' is not a class, namespace, or enumeration RingDeque<T>::Iterator::reference MyIterator::operator*() const { ^ ringDeque.cpp:46:1: note: 'MyIterator' declared here using MyIterator = typename RingDeque<T>::Iterator; ^ 2 errors generated.
I would just use a trailing return type and be done with it. template <typename T> auto RingDeque<T>::Iterator::operator*() const -> reference { //... some implementation } If you really want to use an alias template, then you mustn't forget it's also, as the name suggests, a template. template <typename T> using MyIterator = RingDeque<T>::Iterator; template <typename T> typename MyIterator<T>::reference RingDeque<T>::Iterator::operator*() const { //... some implementation }
70,827,559
70,827,586
I can't find how to add an object to a list of objects
I'm trying to add an object to a list of object the equivalent of myList.append() in python. I've tried insert(), push_back() doesn't work because it's a list of objects. I've tried new() and delete but doesn't work and i don't understand how it works. there's some code missing cause else i cant send th message(too many code) struct point{ int x; int y; int xp; int yp; }; point lines[1]; point pre[1]; int main(){ while(window.isOpen()){ while(window.pollEvent(event)){ if((event.type == Event::KeyPressed) && (event.key.code == Keyboard::Enter) && (!fullscreen)) { fullscreen = true; window.create(VideoMode(1920, 1080), "Project_1", (fullscreen ? Style::Fullscreen : Style::Resize|Style::Close)); text.setString("Press 'Escape' to exit fullscreen!"); } else if((event.type == Event::KeyPressed) && (event.key.code == Keyboard::Escape) && (fullscreen)) { fullscreen = false; window.create(VideoMode(1920, 1080), "Project_1", (fullscreen ? Style::Fullscreen : Style::Resize|Style::Close)); } if(event.type == Event::Closed){ window.close(); } if(event.type == Event::MouseButtonPressed){ point * lines = new point[int(sizeof(lines)/sizeof(lines[0]))+1]; delete lines; text.setString(to_string(sizeof(lines)/sizeof(lines[0]))); cout<<to_string(sizeof(lines)/sizeof(lines[0]))<<endl; }
You can not add to an array in c++ and other low level languages. You will need to use a vector for your case https://www.geeksforgeeks.org/vector-in-cpp-stl/ Vectors are dynamic arrays which can be added to and removed from. Define like so: vector<point> lines; And use the following cmds to manipulate a vector from the above reference: push_back() pop_back() insert()
70,827,560
70,827,622
Another Defined Symbols Not Found for Architecture x86_64
I'm relatively new to CPP, currently in my second class for it, and while I was trying to compile a lab for my class I keep getting this error. I thought it might have something to do with file path but that doesn't seem to the be the case, does anyone have any suggestions? Here is the code: #include <iostream> #include <string> using namespace std; class personType { private: string firstName; string lastName; public: void setName (string, string) { cin >> firstName; cin >> lastName; } const string getFirstName() { return firstName; } const string getLastName() { return lastName; } void print() { cout << firstName << ", " << lastName << endl; } personType(string = "", string = ""); }; int main() { personType John; John.setName("John", "Doe"); John.getFirstName(); John.getLastName(); John.print(); return 0; } Here is the compiler error message: Undefined symbols for architecture x86_64: "personType::personType(std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator >, std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator >)", referenced from: _main in CS200Lab1-022e17.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) Build finished with error(s).
The problem is your class has a method name with no code. personType(string = "", string = ""); The error message is simply telling you there is a declaration for personType::personType(string,string) but it can't find any definition code for this method. You can remove this line, as it is not necessary, and the compiler will add an implicit constructor with no parameters automatically. Alternatively you can add a body of code for this constructor: personType(string first = "", string last = "") { // code here } Maybe your intention is something like this: #include <iostream> #include <string> using namespace std; class personType { private: string _firstName; string _lastName; public: void setName(string firstName, string lastName) { _firstName = firstName; _lastName = lastName; } const string getFirstName() { return _firstName; } const string getLastName() { return _lastName; } void print() { cout << _firstName << ", " << _lastName << endl; } personType(string firstName = "", string lastName = "") { _firstName = firstName; _lastName = lastName; } }; int main() { personType John; John.setName("John", "Doe"); John.getFirstName(); John.getLastName(); John.print(); return 0; }
70,827,819
70,828,500
can anyone help me with my linked list error please?
There is an issue with my code. I need to write a program that creates a linked list and performs insertion, deleting from the beginning, deleting from the end, and printing. Everything in the program works fine, but the delete the first node function. It throws an error in the printing function (posted a picture of the error below). Does anyone know what seems to be the problem? The function that deletes the last node works and prints perfectly. LINKED LIST PROGRAM: struct Node { int data; Node* next; }; void insert(Node** head,int n) //insertion method { Node* newNode = new Node; newNode->data = n; newNode->next = (*head); (*head) = newNode; } Node* deleteFront(struct Node* head)//deleting first node in the list { if (head == NULL) return NULL; else { Node* t = head; head = head->next; free(t); t = NULL; } return head; } Node* deleteEnd(struct Node* head)//deleting last node in the list { if (head == NULL) return NULL; else if (head->next == NULL) { free(head); head = NULL; } else { Node* prev = head; Node* prev2 = head; while (prev->next != NULL) { prev2 = prev; prev = prev->next; } prev2->next = NULL; free(prev); prev = NULL; } return head; } void printLL(Node* h) { while (h != NULL) { cout << h->data << " "; h = h->next; } cout << endl; } int main() { cout << "Linked list question 2: " << endl; //linked list question 2 Node* n = NULL; insert(&n, 60); insert(&n, 40); insert(&n, 20); printLL(n); deleteFront(n); cout << "after deleting first node: "; printLL(n); deleteEnd(n); cout << "after deleting last element: "; printLL(n); } A picture of the error: error output
Take it easy. I read your code and there are no errors in logic. However, there are some mistakes in the selection of parameters. It is not necessary to use ** in the insert. Using * can meet the requirements, and use & to achieve assignment to the linked list. The same is true for deleteFront and deleteEnd. I modified your code and now the program can run normally, hope it helps. #include<iostream> using namespace std; struct Node { int data; Node* next; }; void insert(Node*& head, int n) //insertion method { Node* newNode = new Node; newNode->data = n; newNode->next = head; head = newNode; } Node* deleteFront(struct Node*& head)//deleting first node in the list { if (head == NULL) return NULL; else { Node* t = head; head = head->next; free(t); t = NULL; } return head; } Node* deleteEnd(struct Node*& head)//deleting last node in the list { if (head == NULL) return NULL; else if (head->next == NULL) { free(head); head = NULL; } else { Node* prev = head; Node* prev2 = head; while (prev->next != NULL) { prev2 = prev; prev = prev->next; } prev2->next = NULL; free(prev); prev = NULL; } return head; } void printLL(Node* h) { while (h != NULL) { cout << h->data << " "; h = h->next; } cout << endl; } int main() { cout << "Linked list question 2: " << endl; //linked list question 2 Node* n = NULL; insert(n, 60); insert(n, 40); insert(n, 20); printLL(n); deleteFront(n); cout << "after deleting first node: "; printLL(n); deleteEnd(n); cout << "after deleting last element: "; printLL(n); }
70,828,764
70,828,903
Why can't we specialize concepts?
The syntax that works for classes does not work for concepts: template <class Type> concept C = requires(Type t) { // ... }; template <class Type> concept C<Type*> = requires(Type t) { // ... }; MSVC says for the line of the "specialization": error C7606: 'C': concept cannot be explicitly instantiated, explicitly specialized or partially specialized. Why cannot concepts be specialized? Is there a theoretical reason?
Because it would ruin constraint normalization and subsumption rules. As it stands now, every concept has exactly and only one definition. As such, the relationships between concepts are known and fixed. Consider the following: template<typename T> concept A = atomic_constraint_a<T>; template<typename T> concept B = atomic_constraint_a<T> && atomic_constraint_b<T>; By C++20's current rules, B subsumes A. This is because, after constraint normalization, B includes all of the atomic constraints of A. If we allow specialization of concepts, then the relationship between B and A now depends on the arguments supplied to those concepts. B<T> might subsume A<T> for some Ts but not other Ts. But that's not how we use concepts. If I'm trying to write a template that is "more constrained" than another template, the only way to do that is to use a known, well-defined set of concepts. And those definitions cannot depend on the parameters to those concepts. The compiler ought to be able to compute whether one constrained template is more constrained than another without having any template arguments at all. This is important, as having one template be "more constrained" than another is a key feature of using concepts and constraints. Ironically, allowing specialization for concepts would break (constrained) specialization for other templates. Or at the very least, it'd make it really hard to implement.
70,828,943
70,828,970
"binary 'operator+' has too many parameters
Trying to implement operator overloading using the following code: class Number { T value; public: Number(T v); Number(); Number<T> operator+ (Number<T>&, const Number<T> &); T getValue() { return value; }; }; template <typename T> Number<T>::Number(T val):value(val) { } template <typename T> Number<T> Number<T>::operator+ (Number<T>& lhs, const Number<T> & rhs) { return lhs.value + rhs.value; } Trying to emulate similar examples found online, but this attempt generates several compiler errors '{' missing function header (old-style format list?) binary 'operator +' has too many parameters class template "Number" has no member "operator+" Number<T> Number<T>::operator+ (Number<T>& lhs, const Number<T> & rhs) With all the decisions: whether or not to include "<T>"; whether or not to use references for sends and returns; whether or not to use "const" and/or "friend"; and whether or not to use "this", "new" and/or "->"; it's confusing enough to search for outside help :). Any idea what (many things) I'm doing wrong? Thanks for your consideration
You're forgetting about the implicit this parameter that are present as the first parameter in a non-static member function. To solve your probelm just remove the extra first parameter from operator+ as shown below: template<typename T> class Number { T value; public: Number(T v); Number(); Number<T> operator+ (const Number<T> &);//REMOVED UNNECESSARY PARAMETER T getValue() { return value; }; }; template <typename T> Number<T>::Number(T val):value(val) { } template <typename T> Number<T> Number<T>::operator+ (const Number<T> & rhs) { //REMOVED UNNECESSARY PARAMETER return value + rhs.value;//CHANGED lhs.value to value } The output of the program can be seen here.
70,829,394
70,829,664
VS Code - Failing to take input from terminal
I am fairly new to tweaking with the settings in VS Code. I have installed the code runner extension on VS Code. I have also updated the settings to make the code run in terminal, instead of the output tab. This works fine with other languages, but in case of C++, it fails to take inputs and finishes execution as soon as it compiles. What could be causing this?
Go to settings in VS Code, and look for the property "Run in Terminal" under Code Runner settings. Check that box, and update your compiler directory. Once you do this, reload the VS Code window and run your code again, the terminal should take inputs now.
70,829,490
70,829,552
Fill an array from For loops to create all the possibilities from 4 letters
I'm trying ton convert the following code from c++ to java and as I'm a beginner student in Java I have errors when tryin to assign the char to tabtemp. I didnt found examples with multiple For loops #include <iostream> #include <string> #include <vector> using namespace std; int main() { for (char a = 97; a <= 100; a++) for (char b = 97; b <= 100; b++) for (char c = 97; c <= 100; c++) for (char d = 97; d <= 100; d++) { string tabtemp = { a,b,c,d }; { cout << tabtemp << endl; } } return 0; } 1st try in java public class Alpha { public static void main(String[] args) { for (char a = 97; a <= 100; a++) { for (char b = 97; b <= 100; b++) for (char c = 97; c <= 100; c++) for (char d = 97; d <= 100; d++); char[] tabtemp = {a,b,c,d}; System.out.println(tabtemp); } } } Thanks
you can do something like this in Java: char[] tabtemp = null; for (char a = 97; a <= 100; a++) { for (char b = 97; b <= 100; b++) { for (char c = 97; c <= 100; c++) { for (char d = 97; d <= 100; d++) { tabtemp = new char[]{a, b, c, d}; } } } System.out.println(tabtemp); }
70,830,334
70,830,778
Is manually unlocking associated mutex of a RAII wrapper (like st::unique_lock) always a UB?
I wonder if manually unlocking a mutex associated with a RAII wrapper is always a UB. For example, is it ok if we lock it again before RAII wrapper destroys like this: int i = 0; std::mutex mx_; void foo() { for (int k = 0; k < 10000; k++) { std::unique_lock<std::mutex> lk(mx_); i++; mx_.unlock(); mx_.lock(); i++; } } The reason for my question is that I'm trying to write a small RAII wrapper that upgrades a shared lock to a exclusive lock for a std::shared_mutex and I need to manually lock/unlock std::shared_mutex that is associated with other locks and I wonder if it is UB. Here is my upgrade_lock class: template<typename Mutex> class upgrade_lock { public: using mutex_type = Mutex; explicit upgrade_lock(mutex_type& mx) : mxp_(&mx) { mxp_->unlock_shared(); mxp_->lock(); } ~upgrade_lock() { mxp_->unlock(); mxp_->lock_shared(); } upgrade_lock(const upgrade_lock&) = delete; upgrade_lock& operator=(const upgrade_lock&) = delete; private: mutex_type* mxp_ = nullptr; }; I'm assumed that this class is only used when shared lock is acquired by a thread. And about why unlock/lock pairs is not guarded by another mutex, I think it is not necessary really. I can use this class like this now: int i = 0; std::shared_mutex mx_; void goo() { for (int k = 0; k < 10000; k++) { std::shared_lock<std::shared_mutex> lk(mx_); if (i > 5000) { upgrade_lock<std::shared_mutex> lk2(mx_); i++; } } }
I don't think it's UB if you pair it correctly (and no exception occur as @ DanielLangr said, which would try to unlock a already unlocked mutex) You can pass the lock directly though. template<typename lock_type> class upgrade_lock { public: upgrade_lock(lock_type& src_lock):lock(&src_lock){ lock->unlock_shared(); lock->mutex()->lock(); } ~upgrade_lock() { lock->mutex()->unlock(); lock->lock_shared(); } upgrade_lock(const upgrade_lock&) = delete; upgrade_lock& operator=(const upgrade_lock&) = delete; private: lock_type* lock; }; (code not tested)
70,830,428
70,831,605
Passing Rust vector to C++ function using cpp crate
I am using the cpp crate (https://crates.io/crates/cpp) to run some C++ code from inside Rust. How can I make a vector, that is known to the Rust code available inside the C++ code? First I tried something like this: cpp::cpp!{{ #include <iostream> #include <vector> }} fn call_some_cpp_stuff(mat: &Vec<f64>, n: usize){ let n = n as u32; unsafe{ cpp::cpp!([mat as "std::vector", n as "uint32_t"]{ std::cout << mat[n-1] << std::endl; }); }; } Which results in the following error: error[E0512]: cannot transmute between types of different sizes, or dependently-sized types --> src/numerics.rs:248:20 | 248 | cpp::cpp!([mat as "std::vector<double>", n as "uint32_t"]{ | ^^^ | = note: source type: `&Vec<f64>` (64 bits) = note: target type: `[u8; 24]` (192 bits) = note: this error originates in the macro `__cpp_closure_impl` (in Nightly builds, run with -Z macro-backtrace for more info) For more information about this error, try `rustc --explain E0512`. error: could not compile `rust_dse` due to previous error When trying to use a pointer instead of a std::vector like this: cpp::cpp!{{ #include <iostream> #include <vector> }} fn call_some_cpp_stuff(mat: &Vec<f64>, n: usize){ let n = n as u32; unsafe{ cpp::cpp!([mat as "const double *", n as "uint32_t"]{ std::cout << mat[n-1] << std::endl; }); }; } It compiles, but I get a segmentation fault when trying to access anything but the 0th element of mat inside the C++ code, even when I am 100% sure, that it does have more than 1 element. Any ideas on how to achiev this?
If all you want to do is read the contents of the Rust Vec without mutating, you need to use as_ptr: cpp::cpp!{{ #include <iostream> #include <vector> }} fn call_some_cpp_stuff(mat: &Vec<f64>, n: usize){ let n = n as u32; let mat = mat.as_ptr(); unsafe{ cpp::cpp!([mat as "const double *", n as "uint32_t"]{ std::cout << mat[n-1] << std::endl; }); }; }
70,830,523
70,834,275
QPixmap causes memory leak?
I stream MJPEG from server and update QLabel's QPixmap every time a valid frame received. Memory usage swells in time and I cannot figure out why. Is this a wrong use of QPixmap? case StreamState::Streaming: { int ind_start_bytes = m_buffer.indexOf("\xff\xd8"); int ind_end_bytes = m_buffer.indexOf("\xff\xd9"); if(ind_start_bytes != -1 && ind_end_bytes != -1) { if(ind_start_bytes < ind_end_bytes){ QByteArray image_data = m_buffer.mid(ind_start_bytes, ind_end_bytes + 2); m_buffer = m_buffer.mid(ind_end_bytes+2); QPixmap pmap; if(pmap.loadFromData(image_data, "JPEG")) { setPixmap(pmap.scaled(pmap.size(), Qt::KeepAspectRatio)); } } } } Here's the github link for full code. mjpegstreamer.cpp for related code.
It is the m_buffer that is swelling. The code i posted consumes frames with fifo logic. So I replaced int ind_start_bytes = m_buffer.indexOf("\xff\xd8"); int ind_end_bytes = m_buffer.indexOf("\xff\xd9"); with int ind_start_bytes = m_buffer.lastIndexOf("\xff\xd8"); int ind_end_bytes = m_buffer.lastIndexOf("\xff\xd9"); If by any chance more than one frames exist in the m_buffer, we will be consuming the last one and remove the ones on the left. Problem seems to be solved now. This apparently has nothing to do with QPixmap.
70,830,938
70,840,074
Create macro to generate getters for any class c++
Recently I started thinking how to generalize access to private data members through a generalized class/function by name. The reason is that I have a lot of private members and creating a getter for each one is bothersome. I tried to use preprocessor macros to do the following #define RETURNS(...) -> decltype((__VA_ARGS__)) { return (__VA_ARGS__); } #define GET(classname, name, funcname) auto funcname() RETURNS(classname->name); class foo { private: int a = 1; std::vector<int> b = std::vector<int>(3, 1); std::string c = "pika-chuuu"; public: foo() = default; ~foo() = default; GET(this, a, getter); }; int main(const int argc, char* argv[]) { foo obj; std::cout << obj.getter(); return 0; } This one compiles, but is there a way I can create a getter in foo, which takes the name of a variable at run-time and returns this->(name)? Using this approach I can reduce the code for introducing getters, nevertheless the more data members there are, the more getters I need, but I would like to have one to get access to any data member by name. Do you have any suggestion of how can it be done? I'm looking for a syntax like this: #define RETURNS(...) -> decltype((__VA_ARGS__)) { return (__VA_ARGS__); } #define GET(classname, name) RETURNS(classname->name); class foo { private: int a = 1; std::vector<int> b = std::vector<int>(3, 1); std::string c = "pika-chuuu"; public: foo() = default; ~foo() = default; auto getter(auto x) GET(this, x); }; Here x is the name I put as input, either a,b or c
Revision: As @HolyBlackCat mentioned, there is no need to heap allocation, and you should use the impl class as object directly: class foo{ struct foo_data { int i; std::string s; }; foo_data data; public: template<typename ... Args> foo(Args&& ... args) : data(std::forward<Args>(args)...) {} foo_data const* operator->() const // Returns a pointer to const data { return &data; } }; Then to access the data: int main() { auto f = foo(3, "hello"); std::cout << f->i << f->s; // Accessing data, prints: "3hello" // f->i += 1; // Error: assignment of member in read-only object }
70,830,981
70,832,659
Clean-up a timed-out future
I need to run a function with a timeout. If it didn't return within the given timeout, I need to discard it and fallback to a different method. Following is a (greatly) simplified sample code to highlight the problem. (In reality, this is an always running, highly available application. There I first read from the cache and try to read from the database only if the cache has stale data. However, if the database query took long, I need to continue with the stale data.) My question is, in the case where the future read timed out, do I have to handle the clean-up of the future separately (i.e. keep a copy and check if it is ready time-to-time)? or can I simply ignore it (i.e. keep the code as is). /* DB query can be time-consuming, but the result is fresh */ string readFromDatabase(){ // ... // auto dbValue = db.query("select name from users where id=" + _id); // ... return dbValue; } /* Cache query is instant, but the result could be stale */ string readFromLocalCache(){ // ... // auto cachedVal = _cache[_id]; // ... return cachedVal; } int getValue(){ // Idea: // - Try reading from the database. // - If the db query didn't return within 1 second, fallback to the other method. using namespace std::chrono_literals; auto fut = std::async(std::launch::async, [&](){ return readFromDatabase(); }); switch (fut.wait_for(1s)){ case std::future_status::ready: // query returned within allotted time { auto freshVal = fut.get(); // update cache return freshVal; } case std::future_status::timeout: // timed out, fallback ------ (*) { break; } case std::future_status::deferred: // should not be reached { break; } } return readFromLocalCache(); // quetion? what happens to `fut`? }
My question is, in the case where the future read timed out, do I have to handle the clean-up of the future separately (i.e. keep a copy and check if it is ready time-to-time)? or can I simply ignore it (i.e. keep the code as is). From my personal perspective, it depends on what you want. Under your current (minimal) implementation, the getValue function will be blocked by the future's destructor(see cppreference page and some SO questions). If you do not want the blocking behavior, there are some solutions, as proposed in this question, like: move the future to some outside scope use a detached executor and some handy code/data structure to handle the return status see if you can replace the future with some timeout support I/O operations like select/poll etc.
70,831,267
70,841,175
Trouble dereferencing ip and port from socket pointer
I'm doing a simple send/receive and in order to execute each request in a thread I've set up my handler function like so: UPDATE: Using std::thread and properly closing socket after use. I'm not using a loop for reading atm because I'm just sending small test messages that are well below the 1024 buffer limit. Unfortunately, I'm still getting odd data for the ip and port. int P2PServer::socketReceiveHandler(int s) { struct sockaddr_in *sin = (struct sockaddr_in *)&s; char buffer[1024] = {0}; int reader; reader = read(s, buffer, 1024); if (reader <= 0) { return 0; } else { std::cout << reader << std::endl; // let's see } char ip[INET_ADDRSTRLEN]; int port=0; inet_ntop(AF_INET, &(sin->sin_addr), ip, sizeof(ip)); port = htons(sin->sin_port); strcpy(ip, inet_ntoa(sin->sin_addr)); printf ("Connection from %s:%d\n", ip, port); printf("Connection from: %d.%d.%d.%d", buffer[197], buffer[198], buffer[199], buffer[200]); //int port = 0; // Start with zero port |= buffer[204] & 0xFF; // Assign first byte to port using bitwise or. port <<= 8; // Shift the bits left by 8 port |= buffer[205] & 0xFF; // (so the byte from before is on the correct position) printf(" Port: %d\n\n", port); char const* message = "I am an amazing server!"; std::cout << "received: " << buffer << std::endl; send(s, message, strlen(message) , 0 ); printf("Server : Message has been sent ! \n"); if (close(s) == -1) { p2putils::logit("Close problems"); std::cout << "errno: " << errno << std::endl; } return 0; } The function is called like so: std::thread peerThread (&P2PServer::socketReceiveHandler,this, incomingSocket); peerThread.join(); Here's the output from the server: ./p2pserver 127.0.0.1 10001 Node usage for peers: ./p2pserver <ip> <port> <masternode> If this is not the master node, restart with 3rd parameter P2P Server: 127.0.0.1 is listening on PORT: 10001 Waiting for incoming connections... 23 Connection from 8.233.176.178:0 Connection from: 0.0.0.0 Port: 0 received: I am an amazing client. Server : Message has been sent ! Waiting for incoming connections... Here's the output from the client: ./p2pserver 127.0.0.1 10002 127.0.0.1 P2P Server: 127.0.0.1 is listening on PORT: 10002 Client : Message has been sent ! I am an amazing server! Waiting for incoming connections...
So the function that saved the day is getpeername() Here's my working solution: int P2PServer::socketReceiveHandler(int s) { struct sockaddr_in addr; char buffer[1024] = {0}; int reader; reader = read(s, buffer, 1024); if (reader <= 0) return 0; socklen_t len; len = sizeof(addr); getpeername(s, (struct sockaddr*)&addr, &len); std::cout << "Connection from: " << inet_ntoa(addr.sin_addr) << " : " << ntohs(addr.sin_port) << std::endl; char const* message = "I am an amazing server!"; std::cout << "received: " << buffer << std::endl; send(s, message, strlen(message) , 0 ); printf("Server : Message has been sent ! \n"); if (close(s) == -1) { p2putils::logit("Close problems"); std::cout << "errno: " << errno << std::endl; } return 0; } The partial output is as follows: P2P Server: 127.0.0.1 is listening on PORT: 10001 Waiting for incoming connections... Connection from: 127.0.0.1 : 58560
70,832,007
70,832,118
What is the construction order in a "diamond problem" where a class is derived from three base classes?
Below is an example code of what I am asking. The output will be XXbBACY, but I don't understand why. #include <iostream> using namespace std; class X { public: X() { cout << 'X'; } X(char c) { cout << 'X' << c; } }; class A : virtual X { public: A() : X('a') { cout << 'A'; } }; class B : X { public: B() : X('b') { cout << 'B'; } }; class C : virtual X { public: C() : X('c') { cout << 'C'; } }; class Y : A, virtual B, C { public: Y() { cout << 'Y'; } ~Y() {} }; int main() { Y y; return 0; } From my understanding, when we create the object y of class Y, because not all the base classes are virtually derived from the class X (B specifically), Y will have 3 instances of class X in it. The first constructor called when constructing the object y will be the constructor of class B because it is virtually derived from class Y, but before constructing the class B, an instance of class X will have to be created and because B() : X('b') { cout << 'B'; } is the default constructor of class B, X(char c) { cout << 'X' << c; } will be called in class X. Which will print Xb. Now we return to class B where the default constructor will print B, and then back to class Y Now an instance of class A and class C will similarly be constructed leaving us with an output of: XbBXaAXcCY My understanding seems to be completely wrong, because the output is XXbBACY, how can this be?
Construction order is always this: First all (direct or indirect) virtual bases, ordered depth-first declaration-order. Obviously at most one of any type. Next, the non-virtual bases in declaration order. All other members in declaration order. Finally, the ctor body. Now you may safely call virtual functions, directly or indirectly, and they will resolve based on the currently running ctor. In your case that means: virtual X from Y::A::X. virtual B from Y::B: (First step: X from Y::B::X.) A from Y::A. X virtual base already done. C from Y::C. X virtual base already done. Destruction order reverses that.
70,832,270
70,832,396
std::unique_ptr, pimpl and object lifetime
The following example compiles with both gcc 11 on Linux (GNU STL) and clang 12 on FreeBSD (Clang STL). On Linux, it runs and prints values 1 and 2. On FreeBSD, it prints value 1 and then crashes with a SEGV. I don't quite understand the object lifetimes -- so the whole thing may be UB and the runtime behavior might not be relevant. I do know that the implementation of std::unique_ptr between those two STLs differs in an important way: Clang STL resets the internal pointer of a std::unique_ptr to nullptr at the start of the destructor, while GNU STL leaves the pointer alone. #include <iostream> #include <memory> struct C { struct Private { C* m_owner; int m_x; Private(C* owner) : m_owner(owner), m_x(0) {} ~Private() { m_owner->cleanup(); } void cleanup() { std::cout << "Private x=" << ++m_x << '\n'; } }; std::unique_ptr<Private> d; C() { d = std::make_unique<Private>(this); } ~C() = default; void cleanup() { d->cleanup(); } }; int main(int argc, char **argv) { C c; c.cleanup(); // For display purposes, print 1 return 0; // Destructors called, print 2 } Output on FreeBSD: Private x=1 Segmentation fault (core dumped) and a snippet of backtrace: * thread #1, name = 'a.out', stop reason = signal SIGSEGV: invalid address (fault address: 0x8) frame #0: 0x00000000002032b4 a.out`C::Private::cleanup() + 52 a.out`C::Private::cleanup: -> 0x2032b4 <+52>: movl 0x8(%rax), %esi My reason for thinking this might be UB is this: at return 0, c's lifetime is ending. the destructor ~C() runs. Once the body (defaulted) of the destructor is done, the lifetime of the object is over and using that object is UB. now the destructors for sub-objects (member-objects?) of the object run. the destructor ~std::unique_ptr<Private> runs. It runs the destructor for the held object. the destructor ~Private() uses a pointer to a no-longer-alive object m_owner to call a member function. I'd appreciate an answer that points out if this understanding of object lifetimes is correct. If it's not UB, then there's a separate quality-of-implementation issue (or I should check the d-pointer before calling methods on it, but that seems a bit derpy for a pimpl; then we get if(d)d->cleanup() which is needed with one STL implementation and which is a useless check in another). In the interest of posing a single question: does this code exhibit UB in the statement m_owner->cleanup() (line 9) during the destruction of object c ?
Yes, the lifetime of the object that m_owner refers to has already ended and it's destructor call completed when m_owner->cleanup(); is called. The call is therefore UB.
70,832,564
70,832,680
Are environment variables in C++ writeable?
The function getenv(const char * key) returns char *. Does it mean that I can change some character inside of returned char array? For example char * name = getenv("PROJECT_NAME"); if(name && strlen(name) > 0) name[0] = 'P'; Is it good practice to do this? Should I make my own copy of array? Where are environment variables stored (what part of memory)? Are they avaible till the end of program? Thank you for your answer.
In https://en.cppreference.com/w/cpp/utility/program/getenv: Modifying the string returned by getenv invokes undefined behavior. So you can modify it but doing so leads to undefined behavior. So you shouldn't do it
70,832,667
70,832,753
Get the last element from a std::vector
In the following example, I would like to get an element from my vector. But I don't understand the error: #include <vector> #include <memory> using namespace std; class Foo{ virtual int end() = 0; }; class Bar : public Foo{ int end(){ return 0; } }; int main(){ vector<shared_ptr<Foo>> a; a.push_back(make_shared<Bar>()); shared_ptr<Foo> b = a.pop_back(); } Here the error: g++ test.cpp test.cpp: In function ‘int main()’: test.cpp:21:35: error: conversion from ‘void’ to non-scalar type ‘std::shared_ptr<Foo>’ requested 21 | shared_ptr<Foo> b = a.pop_back(); | ~~~~~~~~~~^~
This is indeed confusing. As said kiner_shah in his comment. You don't want to use pop_back int main(){ vector<shared_ptr<Foo>> a; a.push_back(make_shared<Bar>()); shared_ptr<Foo> b = a.back(); } The pop_back method doesn't return anything.
70,833,153
70,833,703
Swap words in string C++
I'm a new StackOverflow user! i need help. My task is to find two verbs in the string that are in the list (_words[]) and swap them. With string it's not that hard to implement, but I'm only allowed to use char. My idea is this: I split the char(char str[]) array into words, and assign each word to a constant array(str2[]), I do the same with known verbs. Next, I check - if the word in the first array matches the known verb, then I assign the number (j) to an integer array in order to know the location of this word. Well, then, with the help of a bubble method, I change their places. But that's bad luck, I looked through the debugger, and for some reason when comparing words, even though the words are the same, the check does not pass. (sorry for my English) Could you help me figure out what I'm doing wrong? I will be grateful! #pragma warning(disable:4996) #include <iostream> #include <conio.h> void words() { char str[] = "i like to make programm"; char _words[] = "like make"; char* l1 = strtok(_words, " "); const char* z[10]; const char* str2[10]; const char* temp[1]; int arr_num[2]; int i = 0, control = 0; int word = 0; char* stream; while (l1 != NULL) { z[i] = l1; l1 = strtok(NULL, " "); i++; } for (int i = 0; i < 2; i++) { cout << z[i] << endl; } i = 0; for (int i = 0; i < strlen(str); i++) { if (str[i] == ' ') { word++; } } word++; stream = strtok(str, " "); while (stream != NULL) { str2[i] = stream; if(stream == z[0]) cout << "lol"; stream = strtok(NULL, " "); i++; } for (int i = 0; i < word; i++) { cout << str2[i] << endl; } for (int i = 0; i < 2; i++) { for (int j = 0; j < word; j++) { if ((z[i] == str2[j]) && (control < 3)) { control++; arr_num[i] = j; } } } if (control == 2) { temp[0] = str2[arr_num[0]]; str2[arr_num[0]] = str2[arr_num[1]]; str2[arr_num[1]] = temp[0]; } for (int i = 0; i < word; i++) { cout << str2[i] << " "; } }
Posted only because the OP asked for an alternative algorithm of how this can be done. There are other ways, but this has the benefit of being done entirely in place, using no additional storage besides some pointers and some lengths. This task can be done in-place, by using a utility function to reverse a character sequence, given a pointer and length (or two pointers). You must have numerous other reliable operations at your disposal as well, including the ability to find complete words. (e.g. words that are preceded by whitespace or begin-of-string, and succeeded by whitespace or end-of-string. Write those, and test them thoroughly. Once you've done that, consider the following. String this is a very simple sample of words Test Words very of We start by separating our two words, which you're already doing. Next we find both words, remembering their locations, using your well-tested utility functions. We know their lengths, so we can therefore calculate where they begin, and where they end. this is a very simple sample of words 1111 22 Side note: When doing this, you'll discover the order may be backward. For example, if your word list was of very, then the result would have your word positions looking like this: this is a very simple sample of words 2222 11 It doesn't matter, all that matters is that once you find both words, the word closest to the beginning of the string is the "first" word, and the one coming later is the "second" word from here on out. That said (and now back to our original labeling), reverse the entire segment from the beginning of the first word through the end of the second word, not including any whitespace preceding the first, or succeeding the second: this is a fo elpmas elpmis yrev words 22 1111 Next, reverse the two words in-place at their new homes. this is a of elpmas elpmis very words 22 1111 And finally, reverse all characters past the end of the new first word until (but not including) the beginning of the new second word, including whitespace That means this region: this is a of elpmas elpmis very words xxxxxxxxxxxxxxx and it becomes this: this is a of simple sample very words That's the entire algorithm. Once you find your word locations and extents you're literally four well-place segment reversals from accomplishing your goal. Obviously, care must be undertaken to ensure you do not precede before beginning of string, nor exceed past the end-of-string, should your words being swapped reside in those locations. Update : OP-provided sample. The OP provided a sample, apparently not understanding how the above algorithm applies, so I'm running it through that sample as well Words like eat Sentance I like to eat apples Step 1: Locate the two words, noting their position and lengths. I like to eat apples 1111 222 Step 2: Reverse the full segment from the beginning of the first word through the end of the second. Therefore, the segment marked with 'x' below: I like to eat apples xxxxxxxxxxx becomes this: I tae ot ekil apples 222 1111 Step 3: Reverse each word now that they're in their new locations I eat ot like apples 222 1111 Step 4: Reverse the full segment between the two words, including whitespace. E.g. the segment marked below: I eat ot like apples xxxx becomes this: I eat to like apples And you're done.
70,833,373
70,851,544
Deduce class template arguments from class constuctor
I would like to let compiler deduce partially class template arguments from constructor. The motivation is to write a protocol library where the existance (here the length in bits) of certain data depends of the value of last variable, so a conditional class must be used to model this. The c++ code I want to implement should work like this, but I would like to implement it in a more expressive and simplified way, without having to set all the parameters in the template but leaving compiler deduce them: Coliru link: https://coliru.stacked-crooked.com/a/bb15abb2a9c09bb1 #include <iostream> template<typename T1, typename T2, typename F, int... Ints> struct If : T1 { const T2& condition; constexpr If(const T2& cond) : condition(cond) {} constexpr int bits() { return check() ? T1::bits : 0; } constexpr bool check() { return (F{}(Ints, condition.value) || ...); } }; struct Variable1 { int value{}; static constexpr int bits{ 5 }; }; struct Variable2 { int value{}; static constexpr int bits{ 8 }; }; struct Datagram { Variable1 var1; If<Variable2, Variable1, std::equal_to<int>, 1, 2> var2{ var1 };//It compiles and works OK under c++17. What I have... //If<Variable2> var2{ var1, std::equal_to<int>{}, 1, 2 };// ...what I wish }; int main() { Datagram data; data.var1.value = 0; std::cout << data.var2.bits() << "\n";//must be 0 data.var1.value = 1; std::cout << data.var2.bits() << "\n";//must be 8 data.var1.value = 2; std::cout << data.var2.bits() << "\n";//must be 8 } Is this possible?
The concept you are probably looking for is "type erasure", e.g. via std::function. Something along these lines: template<typename T1> struct If : T1 { std::function<bool()> checker_; template <typename T2, typename F, typename... Args> constexpr If(const T2& cond, F&& f, Args&&... args) : checker_([=, &cond]() { return (f(args, cond.value) || ...); }) {} constexpr int bits() { return check() ? T1::bits : 0; } constexpr bool check() { return checker_(); } }; Demo
70,833,377
70,833,409
Why is C++ preincrement addition uniquely different from javascript, C#, etc.? (Sequence points?)
I have been trying to digest such references as Undefined behavior and sequence points and am interested as to why the outcome of the C++ variation of the following code is different from the outcome of a C# or Javascript variation of this code (see code samples, below). Can you elaborate on this, what I think is an anomaly in this C-family variation? I appreciate it. EDIT: This question is about a code example that would never exist in a real-world code base. The construct is undefined in C++, and why would you ever do such a thing? As @Sebastian says, You have two pre-increments and one addition. C++ choses (in this case with your compiler, no guarantee) to combine the two pre-increments to +2 and then sum up 7+7. That is more performant. If you want to have a defined order, use more variables or put the operations into functions. You could write i = (i + 1) + (i + 2). That ist much easier to understand for humans, too! EDIT: This appears then to be just a mind f**k for interviewees during a job interview. Best answer: "This is undefined." C++ Code Example ( Link: https://g.nw7us.us/3nVy02j ) // CPP program to demonstrate special // case of post increment operator #include <iostream> using namespace std; int main() { int i = 5; cout << "Value of i before pre-incrementing"; cout << "\ni = " << i; i = ++i + ++i; cout << "\nValue of i after pre-incrementing"; cout << "\ni = " << i; cout << "\n+++++++++++++++++++++\n"; i = 5; cout << "Value of i before pre-incrementing"; cout << "\ni = " << i; i = ++i; cout << "\ni = " << i; i = i + ++i; cout << "\ni = " << i; return 0; } Output: Value of i before pre-incrementing i = 5 Value of i after pre-incrementing i = 14 +++++++++++++++++++++ Value of i before pre-incrementing i = 5 i = 6 i = 14 Now, here is the C# version ( link: https://g.nw7us.us/3nScCLz ) using System; public class Program { public static void Main() { Console.WriteLine("Hello World"); int i = 5; Console.WriteLine("i = [" + i + "]"); i = ++i + ++i; Console.WriteLine("i = [" + i + "]"); } } Output: Hello World i = [5] i = [13] Finally, a Javascript example ( link: https://onecompiler.com/javascript/3xravf59k ) console.log("Preprocessing example..."); let i = 5; console.log("i = [" + i + "]") i = ++i + ++i; console.log("i = [" + i + "]") Output: Preprocessing example... i = [5] i = [13] I appreciate clarification on sequence points in C++, as it applies to this example.
Because (1) you never need to write cumbersome expressions like i = ++i + ++i and (2) C and C++ are all about not giving away performance, the behaviour is undefined. (Although C++17 does define some more of these class of expressions). On (2), different architectures may be able to optimise increments differently. That would be given away - with no real advantage gained - if the behaviour of expressions such as yours were defined.
70,833,470
70,835,380
How do I exit the code at a certain breaking point in a function
In this function to calculate the factorial of a number: int fact(int n) { if (n == 0 || n == 1) return 1; else return n * fact(n - 1); } How do I add a condition if(n<0) cout <<"Error negative values are not accepted"; //Here I want to add something that makes me exit the function and stop the code after the cout statement is printed
You can use std::exit() after the cout statement
70,833,693
70,833,806
How to avoid double search on std::unordered_map AND avoid calling factory function when not required when implementing a cache
I've been implementing a cache based on std::unordered_map. I want to avoid calling the factory function that generates the value if the value is already stored but I also want to avoid running the search on the map twice. #include <unordered_map> struct Value { int x; Value & operator=(Value const &) = delete; }; using Cache = std::unordered_map<int, Value>; Value make_value(int i){ // Imagine that this takes a time ok! i = i + 1; return Value{i}; } // This has double search template <typename F> Value & insert_a(Cache & cache, int key, F factory) { auto i = cache.find(key); if(i==cache.end()){ auto r = cache.try_emplace(key,factory(key)); return r.first->second; } return i->second; } // This runs the factory even if it is not required template <typename F> Value & insert_b(Cache & cache, int key, F factory) { auto r = cache.try_emplace(key,factory(key)); return r.first->second; } int main(){ std::unordered_map<int,Value> map; insert_a(map,10,make_value); insert_b(map,10,make_value); return 0; } I have two simplified implementations of insert demonstrating how one could build the cache. The insert_a uses find first to detect if the item exists and only if it doesn't calls the factory to get the value. Two searches on the container are performed. The insert_b calls try_emplace and just returns the stored value. This is obviously bad because the factory is called even if the value is already there. It seems I want a middle ground where I pass the factory function directly to try_emplace and internally it is called only if required. Is there a way to simulate this? This is not a question in general about how to build a cache. I am aware of multi-threading issues, const correctness and mutable keywords. I am specifically asking how to get both Single search of the container Only call factory if required Please note that I have deleted the copy assign operator deliberately for the Value class. An obvious answer is to insert a default value first and then overwrite it. Not all classes are copy assignable and I want to support those. There is a sandbox to play with https://godbolt.org/z/Gja3MaGWf
You can use a lazy factory. Ie one that only calls the actual factory when needed: #include <unordered_map> #include <iostream> struct Value { int x; Value & operator=(Value const &) = delete; }; using Cache = std::unordered_map<int, Value>; Value make_value(int i){ // Imagine that this takes a time ok! i = i + 1; return Value{i}; } template <typename F> Value & insert_b(Cache & cache, int key) { auto r = cache.try_emplace(key,F{key}); return r.first->second; } // call the factory when needed struct ValueMaker { int value; operator Value() { std::cout << "called\n"; return make_value(value); } }; int main(){ std::unordered_map<int,Value> map; insert_b<ValueMaker>(map,10); insert_b<ValueMaker>(map,10); return 0; } Output is called because ValueMaker::operator Value is only called once when the element is inserted into the map. On the second call, the value maker (which is just a slim wrapper) is not converted to a Value because the key is already in the map. I tried to change as little as possible on your code. For your actual code you might want to get rid of the two factories (make_value and ValueMaker) and use only one. The key point is to pass some light wrapper to try_emplace that only triggers the construction of the actual value when it is converted to Value.
70,833,795
70,834,122
Weird compiler behavior on LeetCode
I was solving LeetCode problem: 7. Reverse Integer, for testing purposes I was printing some values (long long x2 and long long x3). Here, value of xRough were assigned to x2 and x3 if x or xRough is negative, otherwise an undefined value will be assined. But, LeetCode compiler assigns value of xRough to x2 and x3 even if x is positive (instead of assigning an undefined value). I tested this code on different compilers and they gave undefined values of x2 and x3 when x is positive. But LeetCode compiler is giving the wrong result. Isn't this wrong or weird behavior of the LeetCode compiler or am I missing some point here? class Solution { public: int reverse(int x) { long long x2, x3; long long xRough = (long long) x; if (xRough < 0){ x2 = x3 = (-1) * xRough; } cout<<x2<<" "<<x3<<" "<<xRough<<endl; return 0; } }; I have also got Accepted with this weird behavior of compiler. The accepted code is: class Solution { public: int reverse(int x) { long long flag = 0, y, x2, x3, xRough = (long long) x; long long theNum = 0, i = 1; if (xRough < 0) x2 = x3 = std::abs(xRough); while (1) { x2 = x2 / 10; i = i * 10; if (x2 == 0) break; } i = i / 10; while (1) { y = x3 % 10; x3 = x3 / 10; theNum = theNum + y * i; i = i / 10; if (x3 == 0) break; } if (x < 0) { if (theNum > std::pow(2, 31)) return 0; else return (-1) * theNum; } else { if (theNum > (std::pow(2, 31) - 1)) return 0; else return theNum; } } };
In your function: class Solution { public: int reverse(int x) { long long x2, x3; long long xRough = (long long) x; if (xRough < 0){ x2 = x3 = (-1) * xRough; } cout<<x2<<" "<<x3<<" "<<xRough<<endl; return 0; } }; There are two cases one has to distinguish. Either xRough < 0 is true or it is false. When it is true x2 will get a value assigned and everything works as you expect. When it is false then the code tries to print the values of x2 and x3, but they are not initialized. They have indeterminate values. You cannot do anything with indeterminate values without invoking undefined beahvior. The only way the function has defined output is when xRough < 0 is true. When it is false the output can be anything. Hence, completely ignoring the case of xRough < 0 being false is allowed for the compiler. Thats what compilers are built for, thats why they are good in optimizing code, they can eliminate paths in the code that are never taken (or may never be taken because the outcome is undefined anyhow).
70,834,127
70,837,717
Using cpplint to find typos in variable initialization
I want to check my code to find typos like this: bool check; check == true; // should be: check = true; This is a valid code in C/C++, so I want to use cpplint to find code occurrences of this type. What cpplint configuration should I use?
This typo indeed can be left unnoticed. I'd suggest you not to rely on default compiler configuration. Assume following code: int main() { int check; check == 1; } When built with gcc main.c -o main the compiler will not produce any warnings at all. (Ubuntu 20.04.1, GCC 9.3.0). However, when built with gcc main.c -o main -Wall: main.c: In function ‘main’: main.c:4:8: warning: statement with no effect [-Wunused-value] 4 | check == 1; | ~~~~~~^~~~ You don't need cpplint for this kind of typos. That's an overkill.