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,037,656
70,037,937
Expecting function body despite it being provided
I have a base class called Node which defines two functions: indent and toString. The former will be used by all derived classes without overriding, however the latter will be overridden in the derived classes. Node.hpp #ifndef NODE_H #define NODE_H #include <string> #include <vector> #include <memory> class Node { public: virtual std::string toString(int level) const {}; std::string indent(int level); }; #endif Node.cpp #include "Node.hpp" std::string Node::indent(int level) { std::string indt; for(int i = 0; i < level; i++) { indt += "\t"; } return indt; } I have a derived class FunctionNode which wants to override toString in node.hpp. FunctionNode.hpp #ifndef FUNCTION_NODE_H #define FUNCTION_NODE_H #include "TypeNode.hpp" #include "ParamsNode.hpp" #include "BlockNode.hpp" #include "DeclarationNode.hpp" class FunctionNode : public DeclarationNode { std::shared_ptr<TypeNode> type; std::string name; std::shared_ptr<ParamsNode> paramList; std::shared_ptr<BlockNode> block; public: FunctionNode(std::shared_ptr<TypeNode> type, const std::string &name, std::shared_ptr<ParamsNode> paramList, std::shared_ptr<BlockNode> block) : type(std::move(type)), name(name), paramList(std::move(paramList)), block(std::move(block)) {} }; #endif Note that DeclarationNode is derived from Node. FunctionNode.cpp #include "FunctionNode.hpp" std::string FunctionNode::toString(int level) const override { std::string indt = indent(level); std::string s = indt + "FunctionNode\n"; s += type->toString(level + 1); s += indt + "\t" + name + "\n"; s += paramList->toString(level + 1); s += block->toString(level + 1); return s; } When I try to compile FunctionNode.cpp to an object using the following line in my Makefile. FunctionNode.o: FunctionNode.cpp FunctionNode.hpp TypeNode.hpp ParamsNode.hpp BlockNode.hpp I get the following error. FunctionNode.cpp:3:55: error: expected function body after function declarator std::string FunctionNode::toString(int level) const override { ^ But I have provided the function body. How do I fix this error?
To override a function in a child class, you need to write the declaration in the class definition. The override specifier will only appear in the header file. Header File class FunctionNode : public DeclarationNode { FunctionNode(...) { ... } std::string toString(int level) const override; }; Source File #include "FunctionNode.hpp" std::string FunctionNode::toString(int level) const { ... }
70,037,732
70,037,887
String is out of range
The task is interchange two parts of a word, which contains the dash (i.e we have 1237-456 but should transform it into 456-1237). Here`s my code, it runs but doesnt shows results as a string is out of range and i dk why. It happens in the 1st for, the second iteration ends in the error+ it happens when strlen is 5 and more. The code: #include <iostream> #include <cstdlib> #include <string> using namespace std; int main() { int u = 0, y = 0; string first, second; int i = 0; string word; cout << "Enter the text: " << endl; getline(cin, word); int l = size(word); int f = word.find('-'); cout << "The word has " << l << " characters" << endl << endl; for (int i = 0; i < f; i++) { first[i] = word[i]; } for (int i = f + 1; i < l; i++) { second[y] = word[i]; y++; } cout << endl << second << " - " << first << endl; }
first and second will not have memory allocated to them. They are initialized as strings of size 0. And for this case I would just use iterators instead of indices (though they could work too, but then you need more manual work to allocate enough room for the target strings and all). All in all I think your code is mixing 'c' and 'c++' style a bit so here is my example: #include <algorithm> // for find #include <iostream> // #include <cstdlib> // <<== this is "c" not C++ // using namespace std; <<== unlearn this int main() { std::string word{ "Mississippi-delta"}; // std::string has a lenght function use that std::cout << "The word has " << word.length() << " characters\n"; // "it" will be an iterator to the location of '-' (if any) auto it = std::find(word.begin(), word.end(), '-'); // it points (beyond) the end of the word if no '-' is found if (it == word.end()) { std::cout << "no '-' found in word"; } else { std::string first{ word.begin(),it }; ++it; // skip '-' std::string second{ it,word.end() }; std::cout << second << "-" << first << "\n"; } return 0; }
70,037,992
70,038,169
Friend class in C++ not allowing access to private member attributes
I recently started C++ and to be completely honest my lecturer isn't much help, I am trying to give a linked list friend access to a node class. From what I can see I have declared everything I need, but I still cant access the Node private members , if somebody could see something im missing that would be great! My node header file: ```#ifndef NodeofBook_h #define NodeofBook_h #include <stdio.h> #include "Book.h" class ListOfBooks; // class NodeofBook { friend class ListOfBooks; private: NodeofBook* next; Book* theBook; public: }; #endif /* NodeofBook_h */ My linked list header file : #ifndef ListOfBooks_h #define ListOfBooks_h #include <stdio.h> #include "NodeofBook.h" class ListOfBooks { private: public: ListOfBooks(); void insertBack(int); void displayList(); int deleteMostRecent(); int deleteInt(int pos); }; #endif /* ListOfBooks_h */ My Linked List cpp file: #include "ListOfBooks.h" int ListOfBooks(){ return 0; } ListOfBooks::ListOfBooks(){ theBook->title = "noTitleYet"; theBook->isbn = 0000; next = NULL; } I am getting an error stating Use of undeclared identifier 'theBook' Any help is really appreciated!
NodeofBook declaring that ListofBooks is a friend class just means that the implementation of ListofBooks can access NodeofBook's private members, but there still needs to be an instance of NodeofBook to access. Its members are not static; non-static member variables are part of some object. That is, just because the ListofBooks is a friend of NodeofBook does not mean that it magically has instances of NodeofBookmembers. A friend relationship is not an is-a relationship like inheritance: it is just about access.
70,038,105
70,038,163
"AddressSanitizer: stack-use-after-scope" when trying to access element of vector of pointers
Why the following code #include <iostream> #include <vector> typedef struct Number { int number = 15; } Number; int main() { std::vector<Number*> nums(5); for (size_t i = 0; i < nums.size(); ++i) { Number num; nums[i] = &num; } std::cout << nums[1]->number << "\n"; return 0; } trigger "AddressSanitizer: stack-use-after-scope", but when i comment line 15: std::cout << nums[5]->number << "\n"; it compiles well? How to fix it? Compile command: clang++ main.cpp -fsanitize=address,undefined -fno-sanitize-recover=all -std=c++17 -O2 -Wall -Werror -Wsign-compare -g -o debug_solution && ./debug_solution
The issue is that you are storing a pointer to a value on the stack that goes out of scope and gets destroyed, leaving a dangling pointer. std::vector<Number*> nums(5); for (size_t i = 0; i < nums.size(); ++i) { Number num; nums[i] = &num; // num goes out of scope here and num[i] has a dangling pointer // to an invalid object } std::cout << nums[1]->number << "\n"; In this toy example, I see no reason to use pointers at all, and the fix would be just to use a std::vector<Number>: std::vector<Number> nums(5); // per comment by @user4581301 // this loop is not really needed, as the constuctor will // default-construct the elements for you for (size_t i = 0; i < nums.size(); ++i) { Number num; nums[i] = num; } std::cout << nums[1].number << "\n"; If you really do need dynamic memory allocation on the heap, you should look at using an std::vector<std::unique_ptr<Number>> or std::vector<std::shared_ptr<Number>> depending on if the object needs to be shared between multiple components.
70,038,139
70,038,468
Append multiple chars to string in C++
Using + is a valid way to append a char to a string in C++ like so: string s = ""; s += 'a'; However, string s = ""; s += 'a' + 'b'; gives a warning: implicit conversion from 'int' to 'char' changes value and does not append a and b characters. Why does the first example append the char and the second does not?
This has to do with operator precedence. Let's take for example the expression: string s = ""; s += '0' + '1';//here + has higher precedence than += Here + has higher precedence than += so the characters '0' and '1' are group together as ('0' + '1'). So the above is equivalent to writing: s+=('0' + '1'); Next, there is implicit conversion from char to int of both '0' and '1'. So '0' becomes the decimal 48 while the character '1' becomes decimal 49. So essentially the above reduces to: s+=(48 + 49); or s+=(97); Now 97 corresponds to the character a and therefore the final result that is appended to the string variable named s is the character a. Now lets apply this to your example: string s = ""; s += 'a' + 'b'; First due to precedence: s+=('a' + 'b'); Second implicit conversion from char to int happens: s+=(97 + 98); So s+=195; So the character corresponding to decimal 195 will be appended to string s. You can try out adding and subtracting different characters to confirm that this is happening. Why does the first example append the char and the second does not? So the fundamental reason is operator precedence.
70,038,541
70,039,208
Customising destruction procedure in std::vector::erase()
When I call the erase function on a vector of type 'T', then the destructor of the elements following the range on which I've called the erase() is called. Is there a way to customise this behaviour? How can I ensure that the destructors of those elements which are being erased are called? Sample Program #include<bits/stdc++.h> enum type { TYPE_DEFAULT, TYPE0, TYPE1, TYPE2, TYPE3, TYPE4, }; char str[][13] = {"TYPE_DEFAULT","TYPE0","TYPE1","TYPE2","TYPE3","TYPE4"}; struct temp { type objType; void printInfo() const { std::cout<<"\nthis-->"<<this; std::cout<<"\nType-->"<<str[objType]<<"\n"; } temp() { objType = type::TYPE_DEFAULT; std::cout<<"\n**Default Constructor**"; printInfo(); } temp(const temp& obj) = default; temp& operator=(const temp& obj) { std::cout<<"\n**operator=**"; objType = obj.objType; printInfo(); return *this; } ~temp() { std::cout<<"\n**Destructor**"; this->printInfo(); std::cout<<"\n"; } }; int main() { std::vector<temp> vec; vec.resize(5); for(int i =0;i<5;i++) { vec[i].objType = (type)(i+1); } std::cout<<"\nPrinting vector before erase. Size->"<<vec.size()<<"\n"; for(const auto&x : vec) { x.printInfo(); } int start = 0; int end = 2; std::cout<<"\nGoing to call erase for vec["<<start<<","<<end<<")\n"; vec.erase(vec.begin()+start,vec.begin()+end); std::cout<<"\nErase has been invoked\n"; std::cout<<"\nPrinting vector Info after erase. Size->"<<vec.size()<<"\n"; for(const auto&x : vec) x.printInfo(); } Output **Default Constructor** this-->0xf9c010 Type-->TYPE_DEFAULT **Default Constructor** this-->0xf9c014 Type-->TYPE_DEFAULT **Default Constructor** this-->0xf9c018 Type-->TYPE_DEFAULT **Default Constructor** this-->0xf9c01c Type-->TYPE_DEFAULT **Default Constructor** this-->0xf9c020 Type-->TYPE_DEFAULT Printing vector before erase. Size->5 this-->0xf9c010 Type-->TYPE0 this-->0xf9c014 Type-->TYPE1 this-->0xf9c018 Type-->TYPE2 this-->0xf9c01c Type-->TYPE3 this-->0xf9c020 Type-->TYPE4 Going to call erase for vec[0,2) **operator=** this-->0xf9c010 Type-->TYPE2 **operator=** this-->0xf9c014 Type-->TYPE3 **operator=** this-->0xf9c018 Type-->TYPE4 **Destructor** this-->0xf9c01c Type-->TYPE3 **Destructor** this-->0xf9c020 Type-->TYPE4 Erase has been invoked Printing vector Info after erase. Size->3 this-->0xf9c010 Type-->TYPE2 this-->0xf9c014 Type-->TYPE3 this-->0xf9c018 Type-->TYPE4 **Destructor** this-->0xf9c010 Type-->TYPE2 **Destructor** this-->0xf9c014 Type-->TYPE3 **Destructor** this-->0xf9c018 Type-->TYPE4 Program Description In the above program, I have a vector(size 5) of a structure named 'temp'. When I call erase on range [0,2), destructors of last 2 elements are called. What do I need to do to call the destructors of first 2 elements instead?
You can't do this with vector. Erase will get rid of the items you want from the vector, but it may not destroy those specific objects. If it is absolutely necessary to call the destructors of the first two elements, consider using a deque if you are going to only insert and erase at the back and the front or a std::forward_list if you don't need random-access. P.S. vector is horrible for insertions and erasures anywhere but the back, as it will have to move all the elements in front of the inserted or erased item.
70,038,663
70,041,211
Overloading operator<< twice in same class for different member variables
Sorry if this question has been asked before, but I'm struggling with overloading the << operator to stream different data into multiple files. I have a Player class, which has the following attributes: char* name; char* password; int hScore; int totalGames; int totalScore; int avgScore; I want to overload the << operator twice: one to stream the name, password and hScore to a "Players.txt" file, and a second overload to stream the totalGames, totalScore and avgScore to a different .txt file which is based off each player's name, e.g. "Player1.txt". Here's what my operator looks like in the Player class: friend ostream& operator<< (std::ostream& os, Player& player) { os << player.name << "\n" << player.encryptPassword((player.password), 3) << "\n" << player.hScore << "\n"; return os; } And here's where I am calling it, from a PlayerLibrary class which contains a vector of Players: ofstream out("Yahtzee.txt"); if (out.is_open()) { for_each(playerList.begin(), playerList.end(), [&out](Player* player) {out << (*player);}); } else { cout << "THERE WAS AN ERROR WRITING TO FILE\n"; } Basically, I want to stream the other variables into another file which is named after the player name, and contains a scorecard for each game they've played. So far it looks like: for (auto it = playerList.begin(); it != playerList.end(); ++it) { auto position = it - playerList.begin(); string filename(playerList[position]->getName()); filename = filename + ".txt"; ofstream out2(filename); for (int i = 0; i < playerList[position]->getNumberOfScorecards(); i++) { out2 << *playerList[position]->getScorecard(i); } } This only streams the scorecard and not the totalGames, totalScore and avgScore, like I want it to. I have tried just moving those variables into the scorecard class, but I feel that it makes more sense to have them where they are. I understand that I can't overload operator<< twice if both overloads have the same parameters, is there another way of going about this? Is there anyway perhaps in the overloaded function to use the output stream and check the name of the .txt file or something. Hope the question makes sense.
Rather than defining an operator<< for Player itself, create a couple of utility types that refer to the Player and have their own operator<<s, let them decide which portions of the Player to stream, eg: class Player { private: std::string name; std::string password; int hScore; int totalGames; int totalScore; int avgScore; ... public: ... std::string getName{} const { return name; } ... std::string EncryptPassword(int arg) const { return ...; } int getNumberOfScorecards() const { return ...; } Scorecard* getScorecard(int index) const { return ...; } class Info { const Player &m_player; void print(std::ostream &os) const { os << m_player.name << "\n" << m_player.encryptPassword(3) << "\n" << m_player.hScore << "\n"; } public: Info(const Player &player) : m_player(player) {} friend std::ostream& operator<<(std::ostream &os, const Info &info) { info.print(os); return os; } }; friend class Info; struct Stats { const Player &m_player; void print(std::ostream &os) const { os << m_player.totalGames << "\n" << m_player.totalScore << "\n" << m_player.avgScore << "\n"; } public: Stats(const Player &player) : m_player(player) {} friend std::ostream& operator<<(std::ostream &os, const Stats &stats) { stats.print(os); return os; } }; friend class Stats; }; And then you can use them like this: ofstream out("Yahtzee.txt"); if (out.is_open()) { for(auto *player : playerList) out << Player::Info(*player); } else { cout << "THERE WAS AN ERROR WRITING TO FILE\n"; } for (auto *player : playerList) { ofstream out2(player->getName() + ".txt"); out2 << Player::Stats(*player); for (int i = 0; i < player->getNumberOfScorecards(); ++i) { out2 << *player->getScorecard(i); } } Online Demo
70,039,010
70,042,467
Getting a ROS distribution value through c++ code
Is there a way to get the ROS_DISTRO in c++, cz I want to run specific C++ code when ros_distro is melodic, and else if noetic then this code. Ubuntu: 20.04 Thank You.
In C++ you can simply use getenv() to grab environmental variables. import <iostream> int main(){ std::string distro = getenv("ROS_DISTRO"); std::cout << "Got distro: " << distro << std::endl; }
70,039,103
70,039,332
how to check if unique_ptr points to the same object as iterator
Let's consider such method: void World::remove_organism(organism_iterator organism_to_delete) { remove_if(begin(organisms_vector), end(organisms_vector), [](const unique_ptr<Organism>& potential_organism_to_del) { }); } what I'm trying to achieve is to delete organism that iterator points to from vector<unique_ptr<Organism>>, so how am I supposed to compare unique_ptr<Organism> to std::vector<unique_ptr<Organism>>::iterator?
You don't have to search through the vector to find an iterator; you just have to erase it: void World::remove_organism(organism_iterator organism_to_delete) { organism_vector.erase(organism_to_delete); } Or if you want to delete only the element that the unique_ptr points to: void World::remove_organism(organism_iterator organism_to_delete) { organism_to_delete->reset(); }
70,039,132
70,160,714
How to set the required version of C++ redistributables
I created a dll based off a sample project that is several years old. I am building the dll and can register this dll successfully on my computer which has both 2010 and 2015-2019 C++ redistributables installed. When I try to install this same dll on a computer with only 2015-2019 c++ redistributables installed, registration fails. After installing the 2010 c++ redistributables on that machine, the dll installed successfully. I would like to be able to register this dll on a computer with only the 2015-2019 redistributables installed. I assume this has something to do with the configuration of the project which I'm building in Visual Studio 2019. I've poked through all the properties but nothing stands out. Would appreciate someone pointing me in the right direction! Update: The sample I am referring to comes with the Windows sdk and can be found here: C:\Users\user\Source\Repos\Windows-classic-samples\Samples\Win7Samples\winui\shell\appshellintegration\RecipeThumbnailProvider When I opened it up in Visual Studio 2019 it did some kind of update, but doesn't seem to have affected the redistributable it depends on.
This ended up being related to the fact that I'm using JNI and was dependent on jvm.dll. I was using the jvm.dll from Java 8u202. This version of the dll is dependent on the 2010 C++ Redistributables. Starting with Java 8u261 jvm.dll is dependent on the 2017 Redistributables (source). Dependency Walker is outdated, but this newer tool, Dependencies, worked with my dll.
70,039,144
70,039,278
Longest common subsequence of more than 1 Letter in a string
I'm trying to find the LCS of more than one letter in two strings using a k value. For example, if k = 3 s1 = "AAABBBCCCDDDEEE" s2 = "AAACCCBBBDDDEEE" then the LCS would be 4: "AAABBBDDDEEE" or "AAACCCDDDEEE", another example is if k = 2 s1 = "EEDDFFAABBCC" s2 = "AACCDDEEBBFF" then the LCS would be 2: "EEBB", "EEFF", "DDFF", "DDBB", ... and so on. How would I be able to do it so that more than one character is in each cell of the table and if the characters are not equal I would have to use a sort, i.e. "EF" == "FE"
Use std::is_permutation to find if two strings contain the same characters. To store more than one character in each "cell of the table" use std::string. For any questions on c++, go here. EDIT: Here is a demo of substr's usage: std::string s{"AAABBBCCCDDD"}; std::cout << s.substr(3, 3) << std::endl; // BBB std::vector<std::string> substr_table; substr_table.reserve(4); // reserve space for elements for(std::size_t i{}; i < s.size(); i += 3){ // break up s into four substrings substr_table.push_back(s.substr(i, 3)); } std::cout << "[ "; std::copy( substr_table.cbegin(), substr_table.cend(), std::ostream_iterator<std::string>(std::cout, ", ") ); // Print vector std::cout << "]\n"; // OUTPUT: [ AAA, BBB, CCC, DDD,]
70,039,351
70,039,712
Is a named rvalue reference "ref" a xvalue?
If an xvalue is a value that is at the end of its lifetime, what is a named rvalue reference if not an lvalue or xvalue (because it is not expiring and is movable)?
Read this part carefully: In C++11, expressions that: have identity and cannot be moved from are called lvalue expressions; have identity and can be moved from are called xvalue expressions; do not have identity and can be moved from are called prvalue ("pure rvalue") expressions; do not have identity and cannot be moved from are not used[6]. The expressions that have identity are called "glvalue expressions" (glvalue stands for "generalized lvalue"). Both lvalues and xvalues are glvalue expressions. The expressions that can be moved from are called "rvalue expressions". Both prvalues and xvalues are rvalue expressions. So this means that a named rvalue reference is an lvalue. Go to https://en.cppreference.com/w/cpp/language/value_category for more info. According to the link above, one of properties of rvalues is that Address of an rvalue cannot be taken by built-in address-of operator: &int(), &i++[3], &42, and &std::move(x) are invalid. Now let's look at an example and take advantage of this property: #include <iostream> void getNum( int&& i ) // i is an rvalue reference, meaning that it can // bind to both xvalues and prvalues { std::cout << "i: " << i << " --- Address: " << &i << '\n'; // notice how the // & operator works for i i += 50; std::cout << "i: " << i << " --- Address: " << &i << '\n'; // also here } int main() { getNum( 35 ); // in this case, we pass it a prvalue std::cout << '\n'; int number { 23 }; // number is an lvalue getNum( std::move( number ) ); // and in this case we pass it an xvalue // since std::move(number) returns an xvalue } The output will be similar to the following: i: 35 --- Address: 0x4f4b9ff62c i: 85 --- Address: 0x4f4b9ff62c i: 23 --- Address: 0x4f4b9ff628 i: 73 --- Address: 0x4f4b9ff628 As you can see, the address of operator& does in fact return the address of i. This clearly shows that a variable of type rvalue reference T&& is an lvalue.
70,039,836
70,040,374
What is the correct way to use fmt::sprintf?
I'm trying to optimize my software and to do that I need to change the way I store and draw things. Many people say that fmt is way faster than iostream at doing those things, yet I'm sitting here and trying to understand what I did wrong. The old code is working: auto type = actor->GetName(); char name[0x64]; if (type.find("AI") != std::string::npos) sprintf(name, "AI [%dm]", dist); The new one isn't: auto type = actor->GetName(); char name[0x64]; if (type.find("AI") != std::string::npos) fmt::sprintf("AI [%dm]", dist); What am I doing wrong?
As @NathanPierson mentioned in comments, fmt::sprintf() return a std::string, which you are ignoring. fmt::sprintf() does not fill a char[] buffer (not that you are passing one in to it anyway, like you were with ::sprintf()). Change this: char name[0x64]; fmt::sprintf("AI [%dm]", dist); To this: std::string name = fmt::sprintf("AI [%dm]", dist); And then you can use name as needed. If you need to pass it to a function that expects a (const) char*, you can use name.c_str() or name.data() for that purpose.
70,040,154
70,040,203
C++ vector prints out weird elements
I'm currently in the process of learning C++ and for that I'm reading the book "C++ Primer". The book is pretty good so far and I have learned a lot however I experienced weird behaviour using a vector and I'm unsure if this is right or if it's a problem from my side. The task is: Read a sequence of words from cin and store the values a vector. After you've read all the words, process the vector and change each word to uppercase. Print the transformed elements, eight words to a line." This is my code: #include <iostream> #include <vector> using namespace::std; int main() { string input; vector<string> svec; while (cin >> input) { svec.push_back(input); for (auto& rows : svec) { for (auto& element : rows) { element = toupper(element); } } int maxWordsPerLine = 0; for (auto word : svec) { if (maxWordsPerLine >= 8) { cout << endl; cout << word; maxWordsPerLine = 1; } else { cout << word; maxWordsPerLine++; } } } } I believe it does the things described in the task but when I type in: Hello thanks for helping I dont know whats wrong with this problem lol The output is: HELLOHELLOTHANKSHELLOTHANKSFORHELLOTHANKSFORHELPINGHELLOTHANKSFORHELPINGIHELLOTHANKSFORHELPINGIDONTHELLOTHANKSFORHELPINGIDONTKNOWHELLOTHANKSFORHELPINGIDONTKNOWWHATSHELLOTHANKSFORHELPINGIDONTKNOWWHATS WRONGHELLOTHANKSFORHELPINGIDONTKNOWWHATS WRONGWITHHELLOTHANKSFORHELPINGIDONTKNOWWHATS WRONGWITHTHISHELLOTHANKSFORHELPINGIDONTKNOWWHATS WRONGWITHTHISPROBLEMHELLOTHANKSFORHELPINGIDONTKNOWWHATS WRONGWITHTHISPROBLEMLOL I hope someone can explain me why this happens and how I can avoid it in the future.
You need to realize there's two steps. First step: read all the words and convert each to uppercase Second steps: print all the words Second step needs to be done after first step is done. However, you have a single while loop. Didn't run it, but simplest change that looks likely to work is: string input; vector<string> svec; while (cin >> input) { svec.push_back(input); for (auto& rows : svec) { for (auto& element : rows) { element = toupper(element); } } } // extra closing bracket for the while int maxWordsPerLine = 0; for (auto word : svec) { if (maxWordsPerLine >= 8) { cout << endl; cout << word << " "; // extra space to separate words maxWordsPerLine = 1; } else { cout << word; maxWordsPerLine++; } }
70,040,267
70,048,689
C++ Include Problem in Event Listener Pattern
I am trying to use EventListener Pattern (instead of Observer) in my project. Basically: Entitys can register themselves as listeners for certain types of Events Entitys can report an Event to EventListener. When an Event is being reported, EventListener will notify Entity instances that are registered to receive this type of Event. The two classes are: class Entity: void Register(std::string type); // calls EventListener::RegisterListener(this, type); void ReportEvent(Event event); // calls EventListener::BroadcastEvent(event); void OnNotify(Event event); // called by EventListener::BroadcastEvent(event); class EventListener: void RegisterListener(Entity* listener, Event event); void BroadcastEvent(Event event); // calls Entity::OnNotify(event) for all relative Entity instances Notice that in Entity::ReportEvent() calls EventListener::RegisterListener(), and EventListener::BroadcaseEvent() calls Entity::OnNotify(). Doing a simple forward declaration cannot enable this dual-linked calling. What should I do? Can I directly #include each other in their .hpp files (Which I highly doubt)?
The solution is way easier than I thought. You can directly #include the header files with each other. Just remember to add the header guards (#ifndef ENTITY_HPP #define ENTITY_HPP #endif).
70,040,627
70,040,671
syntax variants for function pointer as non type template arg
I want to use a function pointer as non type template parameter. I can do it with a predefined alias to the function pointer type with typedef or using. Is there any syntax for the template definition without a predefined type alias? bool func(int a, int b) { return a==b; } //using FUNC_PTR_T = bool(*)(int,int); // OK typedef bool(*FUNC_PTR_T)(int,int); // also OK template < FUNC_PTR_T ptr > void Check() { std::cout << ptr( 1,1 ) << std::endl; } int main() { Check<func>(); } I want to write in in a single step like: // this syntax did not compile... template < bool(*)(int,int) ptr > void Check() { ptr(1,1); } Can someone point me top a valid syntax for that?
You are going to declare a non-type template parameter. You can write template < bool( *ptr )( int, int ) > void Check() { ptr( 1, 1 ); }
70,040,667
70,041,507
Having a hard time figuring out logic behind array manipulation
I am given a filled array of size WxH and need to create a new array by scaling both the width and the height by a power of 2. For example, 2x3 becomes 8x12 when scaled by 4, 2^2. My goal is to make sure all the old values in the array are placed in the new array such that 1 value in the old array fills up multiple new corresponding parts in the scaled array. For example: old_array = [[1,2], [3,4]] becomes new_array = [[1,1,2,2], [1,1,2,2], [3,3,4,4], [3,3,4,4]] when scaled by a factor of 2. Could someone explain to me the logic on how I would go about programming this?
It's actually very simple. I use a vector of vectors for simplicity noting that 2D matrixes are not efficient. However, any 2D matrix class using [] indexing syntax can, and should be for efficiency, substituted. #include <vector> using std::vector; int main() { vector<vector<int>> vin{ {1,2},{3,4},{5,6} }; size_t scaleW = 2; size_t scaleH = 3; vector<vector<int>> vout(scaleH * vin.size(), vector<int>(scaleW * vin[0].size())); for (size_t i = 0; i < vout.size(); i++) for (size_t ii = 0; ii < vout[0].size(); ii++) vout[i][ii] = vin[i / scaleH][ii / scaleW]; auto x = vout[8][3]; // last element s/b 6 }
70,041,880
70,041,926
faster search protocol with large list (c++)
faster search protocol with large list? hello and thanks for reading my post. I'm making some simple autocomplete software that compares the word being entered to every word that matches that word's sequence of letters in the English dictionary. The dictionary contains 400,000 elements so as you could expect it makes for a very long wait time for simple searches. for (int j = 0; j < list.size(); j++) { if (list[j].length() >= input[input.size()-1].length() && input[input.size() - 1] == list[j].substr(0, input[input.size() - 1].length())) { suggestions.push_back(list[j]); } } The code above is probably the least efficient for runtime optimization, but I tried some other things like creating a displacement variable for all 27 letters and then adding that to i. and reducing the maximum to the next letter start (if the index of the first letter, say r, is 400, and the index of the first letter beginning with s is 800, then I would set the range between 400 and 800 instead of 0- 1,500 but it still was slow). Any help would be appreciated
Sort your dictionary. Then you can binary search for the word, since you're matching prefixes only (i.e. you aren't trying to find "hello" by typing "ell"). Also this is very inefficient: input[input.size() - 1] == list[j].substr(0, input[input.size() - 1].length()) That innocent-looking std::string::substr() allocates memory every time! You can use std::string::compare() to do the same comparison without memory allocation, which will make this part ~10x faster.
70,042,092
70,069,628
How to convert a gray8_view_t to a rgb8_view_t by using boost::gil and create a rgb8_image_t object from it?
Since boost::gil does not support gray8_view_t writing for the BMP format, I want to convert gray8_view_t to rgb8_view_t. Here is what I've tried so far. auto rgb_view = boost::gil::planar_rgb_view(width, height, pixels, pixels, pixels, width); pixels contains the raw pixels from the gray8_view_t object, so I let r=g=b=pixels. But boost::gil::write_view(ofstream, rgb_view, boost::gil::bmp_tag()) gives me an empty image. Any idea? Update: By using sehe's example code http://coliru.stacked-crooked.com/a/daa0735f774b727f, I was able to get the color conversation to compile with color_converted_view<gil::rgb8_view_t>. But it does not compile when I use boost::gil::write_view to create an image file from the return value of color_converted_view<gil::rgb8_view_t>. My guess is I will have to create an actual rgb8_image_t object from the return value. How can I convert the return value of color_converted_view<gil::rgb8_view_t> to an actual rgb8_image_t object? Thank you! #include <boost/gil.hpp> #include <fstream> namespace gil = boost::gil; int main() { std::ifstream in("gray8_image_t_sample.jpg", std::ios::binary); gil::gray8_image_t img; gil::read_image(in, img, gil::jpeg_tag()); gil::gray8_view_t gv = gil::view(img); std::ofstream ofs1("test_image.png", std::ios::out | std::ios_base::binary); gil::write_view(ofs1, gv, gil::png_tag()); // This works auto rgbv = gil::color_converted_view<gil::rgb8_view_t>(gv); std::ofstream ofs2("test_image.bmp", std::ios::out | std::ios_base::binary); gil::write_view(ofs2, rgbv, gil::bmp_tag()); // this does not compile } One of the error messages I'm getting \boost\gil\color_base_algorithm.hpp(170,76): error G1A4676F8: no member named 'layout_t' in 'boost::gil::image<boost::gil::pixel<unsigned char, boost::gil::layout<boost::mp11::mp_list<boost::gil::red_t, boost::gil::green_t, boost::gil::blue_t>, boost::mp11::mp_list<std::integral_constant<int, 0>, std::integral_constant<int, 1>, std::integral_constant<int, 2>>>>, false, std::allocator<unsigned char>>' [clang-diagnostic-error] Here is the gray8_image_t file I'm using
Okay the remaining problem was merely a misspecified template argument, color_converted_view expects a destination pixel type: #include <boost/gil.hpp> #include <boost/gil/extension/io/bmp.hpp> #include <boost/gil/extension/io/jpeg.hpp> #include <boost/gil/extension/io/png.hpp> #include <fstream> namespace gil = boost::gil; int main() { std::ifstream in("gray8_image_t_sample.jpg", std::ios::binary); gil::gray8_image_t img; gil::read_image(in, img, gil::jpeg_tag()); gil::gray8_view_t gv = gil::view(img); gil::write_view("input.png", gv, gil::png_tag()); auto rgbv = gil::color_converted_view<gil::rgb8_pixel_t>(gv); gil::write_view("output.png", rgbv, gil::png_tag()); gil::write_view("output.bmp", rgbv, gil::bmp_tag()); } With the resuling files: name preview input.png output.png output.bmp
70,042,094
70,042,169
Nested Structures and using constructor for default value but conversion error
For some reason when I set some default values for the nested structure with a constructor, I get the following error. But it seems the code should work. Can someone tell me where am I going wrong? #include <stdio.h> #include <string.h> #include <iostream> using namespace std; struct smallDude { int int1; int int2; // Default constructor smallDude() { int1 = 70; int2 = 60; } }; struct bigDude { // structure within structure struct smallDude second; }first; int main() { bigDude first = {{2, 3}}; cout<< first.second.int1<<endl; cout<< first.second.int2; return 0; } Error Output: main.cpp:28:28: error: could not convert ‘{2, 3}’ from ‘’ to ‘smallDude’ 28 | bigDude first = {{2, 3}}; | ^ | | |
smallDude has a user-declared default constructor, so it is not an aggregate type, and thus cannot be initialized from a <brace-init-list> like you are attempting to do. There are two way you can fix that: change the smallDude constructor to accept int inputs, like @rturrado's answer shows: struct smallDude { int int1; int int2; // constructor smallDude(int x, int y) : int1{x}, int2{y} {} }; Online Demo get rid of all smallDude constructors completely (thus making smallDude an aggregate) and just assign default values to the members directly in their declarations, eg: struct smallDude { int int1 = 70; int int2 = 60; }; Online Demo
70,042,157
70,042,264
Creating ArrayBuilders in a Loop
Is there any way to create a dynamic container of arrow::ArrayBuilder objects? Here is an example int main(int argc, char** argv) { std::size_t rowCount = 5; arrow::MemoryPool* pool = arrow::default_memory_pool(); std::vector<arrow::Int64Builder> builders; for (std::size_t i = 0; i < 2; i++) { arrow::Int64Builder tmp(pool); tmp.Reserve(rowCount); builders.push_back(tmp); } return 0; } This yields error: variable ‘arrow::Int64Builder tmp’ has initializer but incomplete type I am ideally trying to build a collection that will hold various builders and construct a table from row-wise data I am receiving. My guess is that this isn't the intended use for builders, but I couldn't find anything definitive in the Arrow documentation
What do your includes look like? That error message seems to suggest you are not including the right files. The full definition for arrow:Int64Builder is in arrow/array/builder_primitive.h but you can usually just include arrow/api.h to get everything. The following compiles for me: #include <iostream> #include <arrow/api.h> arrow::Status Main() { std::size_t rowCount = 5; arrow::MemoryPool* pool = arrow::default_memory_pool(); std::vector<arrow::Int64Builder> builders; for (std::size_t i = 0; i < 2; i++) { arrow::Int64Builder tmp(pool); ARROW_RETURN_NOT_OK(tmp.Reserve(rowCount)); builders.push_back(std::move(tmp)); } return arrow::Status::OK(); } int main() { auto status = Main(); if (!status.ok()) { std::cerr << "Err: " << status << std::endl; return 1; } return 0; } One small change to your example is that builders don't have a copy constructor / can't be copied. So I had to std::move it into the vector. Also, if you want a single collection with many different types of builders then you probably want std::vector<std::unique_ptr<arrow::ArrayBuilder>> and you'll need to construct your builders on the heap. One challenge you may run into is the fact that the builders all have different signatures for the Append method (e.g. the Int64Builder has Append(long) but the StringBuilder has Append(arrow::util::string_view)). As a result arrow::ArrayBuilder doesn't really have any Append methods (there are a few which take scalars, if you happen to already have your data as an Arrow C++ scalar). However, you can probably overcome this by casting to the appropriate type when you need to append. Update: If you really want to avoid casting and you know the schema ahead of time you could maybe do something along the lines of... std::vector<std::function<arrow::Status(const Row&)>> append_funcs; std::vector<std::shared_ptr<arrow::ArrayBuilder>> builders; for (std::size_t i = 0; i < schema.fields().size(); i++) { const auto& field = schema.fields()[i]; if (isInt32(field)) { auto int_builder = std::make_shared<Int32Builder>(); append_funcs.push_back([int_builder] (const Row& row) ({ int val = row.GetCell<int>(i); return int_builder->Append(val); }); builders.push_back(std::move(int_builder)); } else if { // Other types go here } } // Later for (const auto& row : rows) { for (const auto& append_func : append_funcs) { ARROW_RETURN_NOT_OK(append_func(row)); } } Note: I made up Row because I have no idea what format your data is in originally. Also I made up isInt32 because I don't recall how to check that off the top of my head. This uses shared_ptr instead of unique_ptr because you need two copies, one in the capture of the lambda and the other in the builders array.
70,042,380
70,044,729
Linker error when using cmake and doctest.h (it's working without cmake)
I have 3 files in my directory "project": doctest.h - the testing library, doctest_main.cpp - a file needed for the library, and tests.cpp - the file with tests. project/doctest_main.cpp: #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" project/tests.cpp: #include "doctest.h" TEST_CASE("Some test_case") { CHECK(2 + 2 == 4); } When I compile everything by hand, it works: project> g++ -std=c++17 -Wall -Wextra -Werror doctest_main.cpp tests.cpp -o a project> ./a I tried to add CMake this way: project/CmakeLists.txt: cmake_minimum_required(VERSION 3.16) project(project) set(CMAKE_CXX_STANDARD 17) add_compile_options(-Wall -Wextra -Werror) add_executable( doctest_main.cpp tests.cpp) Now I need to build CMake. Let's follow the official tutorial: project> mkdir build project/build> cd build project/build> cmake .. # Ok! project/build> cmake --build . # Linker error The error is as follows: /usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/10/../../../x86_64-linux-gnu/Scrt1.o: in function `_start': (.text+0x24): undefined reference to `main' /usr/bin/ld: CMakeFiles/doctest_main.cpp.dir/tests.cpp.o: in function `_DOCTEST_ANON_FUNC_2()': tests.cpp:(.text+0x55): undefined reference to `doctest::detail::ResultBuilder::ResultBuilder(doctest::assertType::Enum, char const*, int, char const*, char const*, char const*)' And a lot of undefined references after that. What should I do?
You've created an executable with the target name doctest_main.cpp and only a single source file. The add_executable should be changed to the following to create a target with the name a which by default results in the executable built being named a (or a.exe on windows): # extra whitespaces/newlines not needed below, but a personal style preference. add_executable(a doctest_main.cpp tests.cpp ) Furthermore I recommend adding header files as sources too, since IDEs like Visual Studio wouldn't list them under the header files belonging to the a target.
70,042,457
70,042,569
Should std::async respect thrown errors?
I'm trying to understand how exceptions are handled asynchronously -- I have a webserver that contains a lambda handler for processing requests (uWebsockets) and it keeps crashing. To simulate the scenario I used std::async void call(function<void()> fn) { std::async([&fn]{ fn(); }); } int main() { try { call([](){ throw std::runtime_error("Oops"); }); } catch (std::runtime_error &e) { cout<<"Caught the error"<<endl; } std::this_thread::sleep_for(std::chrono::milliseconds(100000)); } It seems that running the function inside std::async causes the runtime error to never execute ... the program just exits as if nothing happened... why is this the case?
Let's take this step by step. Let's start with the very definition of what std::async does. It: runs the function f asynchronously (potentially in a separate thread The word "potentially" is a distraction here, but the point is that a different execution thread is going to be involved here. For all practical reasons, the function getting std::async-ed can, and on modern C++ implementations, it will run in a new execution thread. The very reason for having different execution threads, in the first place, is that they are completely independent of their parent execution thread. Different execution threads must properly implement sequencing operations in order to mutually exchange information between themselves, in some form or fashion. try { } catch (std::runtime_error &e) { cout<<"Caught the error"<<endl; } The concept of exceptions, and how try and catch relate to them, is introduced in your average C++ textbook by explaining how try/catch will catch exceptions that occur inside the try/catch block. Once execution leaves the try/catch block, exception handling is no longer in effect, and no exception will be caught (unless execution is inside another try/catch block). It may or may not be immediately clear that combining the concepts of execution threads and this typical explanation of exception handling, you must reach the inevitable conclusion that you can only catch exceptions thrown from the same execution thread. Additionally, in the shown code, there's absolutely nothing that even guarantees that the original execution thread will still be inside the try/catch block when the exception in the other execution thread gets thrown. In fact, it is more likely than not that the parent execution thread has left the original try/catch block and it's sleep_for-ing, when the exception gets thrown. You cannot catch exceptions any more, after leaving the try/catch block. But even if the original execution thread is still inside the try/catch block this won't make any difference, because thrown exceptions can only be caught by the same execution thread, but the function that gets executed by std::async will be running in a completely different execution thread. Edit: std::async([&fn]{ This captures fn by reference. fn is a function parameter that goes out of scope and gets destroyed when the function returns, but there's no guarantee that the new execution thread will reference it before it does. This is immaterial, for the purposes of the mechanics of exception handling (and to how std::async itself handles thrown exceptions), but this needs to be fixed nevertheless.
70,042,606
70,042,844
How to access the Optimization Solution formulated using Drake Toolbox
A c++ novice here! The verbose in the terminal output says the problem is solved successfully, but I am not able to access the solution. What is the problem with the last line? drake::solvers::MathematicalProgram prog; auto x = prog.NewContinuousVariables(n_x); // Cost and Constraints drake::solvers::MathematicalProgramResult result; drake::solvers::OsqpSolver osqp_solver; if (osqp_solver.available()) { // Setting solver options. for (int print_to_console : {0, 0}) { //{0,1} for verbose, {0,0} for no terminal output drake::solvers::SolverOptions options; options.SetOption(drake::solvers::OsqpSolver::id(), "verbose", print_to_console); osqp_solver.Solve(prog, {}, options); } } const auto u = result.GetSolution(x); Another question is that what if I don't wanna choose OSQP and let Drake decide which solver to use for the QP, how can I do this?
You will need to change the line osqp_solver.Solve(prog, {}, options); to result = osqp_solver.Solve(prog, {}, options); currently result is unset. Another question is that what if I don't wanna choose OSQP and let Drake decide which solver to use for the QP, how can I do this? You can do const drake::solvers::MathematicalProgramResult result = drake::solvers::Solve(prog, {}, options); Drake will then choose the solver automatically. For more information, please refer to the tutorial in https://github.com/RobotLocomotion/drake/blob/master/tutorials/mathematical_program.ipynb. It talks about choosing the solver automatically vs manually.
70,042,711
70,042,765
Is it possible to implement command substitution via pipeline?
For example, we have $(ls): int pfd[2]; pipe(pfd); switch (fork()) { case 0: close(pfd[0]); dup2(pfd[1], 1 /*stdout*/); exec('ls', 'ls'); case -1; // Report the error... break; default; break; } wait(nullptr); // Wait until the process is done (it is better to use the waitpid() version) // And now we can read from pfd[0] This code is very conceptual, but am I right? Would it be possible to extract the data from the write end of the pipe after the child process finishes? Than all that's left is just to substitute on substring ($(ls)) to another (the result of the ls itself). Please, correct me if I'm wrong. And even if pfd[0] is a valid file descriptor, which points to a buffer with the result of the execution of ls, how do we read safely from it?
wait(nullptr); This will halt the parent process until the child process terminates. The child process is set up with its standard output hooked up to the write end of a pipe whose read end is opened in the parent process. Pipes' internal buffer size is limited. If the child process generates enough output it will block until the pipe gets read from. But the parent process is now waiting for the child process to terminate before doing anything. This will result in a deadlock. Additionally, it looks like the parent process still has the write end of the pipe opened. If the parent process tries to read from it, and it reads everything, it will block because the write end of the pipe is still open (even after the child process has terminated). So, no matter what you want to do, the write end of the pipe in the parent process should be closed. From that point on you have several options available to you "conceptually" (as you asked). You can focus on reading from the pipe. An end-of-file indication will inform you when the write end of the pipe has closed. The child process has terminated so you can wait() for it now, and get its immediate exit code. This is probably the most common approach. Other approach are also possible, like both reading and keeping an eye on SIGPIPE. Or use signal file descriptors, on Linux, to catch the SIGPIPE in a manner that allows this to be conveniently multiplexed with reading from the pipe (via poll or select). Note that if the child process terminated after writing the pipe, and the parent process has wait() for the child without reading from the pipe, after wait() returns it's possible to read the unread data from the pipe. It'll still be there. But, as I explained, this is fragile, and will break if the child process generates sufficient output to clog up the entire pipe. It's often much simpler to read from the pipe, until an end-of-file indication and then clean up after the child process.
70,042,745
70,042,857
How to correct this arithmetic operation without the need to use fmod?
In c++ this code below shows an error: expression must have integral or unscoped enum type illegal left operand has type 'double' is it possible to correct it without the need to use fmod? # include <iostream> using namespace std; int main() { int x = 5, y = 6, z = 4; float w = 3.5, c; c = (y + w - 0.5) % x * y; // here is the error cout << "c = " << c << endl; return 0; }
You can use type casting to fix it : c = ((int) (y + w - 0.5)) % x * y; To clarify your response in the comments, changing c to type int still don't work as the part (y + w - 0.5) is not evaluated as int but as double. And modulus operation doesn't take that type as an argument. Full modified code : #include <iostream> using namespace std; int main() { int x = 5, y = 6, z = 4; float w = 3.5, c; //c could still stayed as float c = ((int) (y + w - 0.5)) % x * y; //swapped out here cout << "c = " << c << endl; } Output : c = 24. To be clear here, this is only a temporary fix for this case, when you know (y + w - 0.5) is going to have a clear integer value. If the value is something like 0.5 or 1.447, std::fmod is desirable. Here's a post on type conversion rules in an expression regarding interaction between float/double and int/long long : Implicit type conversion rules in C++ operators
70,042,913
70,042,919
How to print out actual object value instead of memory address in gdb?
(gdb) print inputInfo $8 = (SObjectRecInput *) 0x7fffffffced0 For example, when I want to check the value of inputInfo, it prints out: 0x7fffffffced0 And its type is 'SObjectRecInput'. How to actually print out its value?
inputInfo appears to have a pointer type, so dereference it: (gdb) print *inputInfo
70,043,418
70,043,745
Most frequent Alphabet Substring
My Logic is working for smaller input How can I make it better to accepts for larger inputs. Q) The program must accept a string S containing only lower case alphabets and Q queries as the input. Each query contains two integers representing the starting and the ending indices of a substring in S. For each query, the program must print the most frequently occurring alphabet in the specified substring. If two or more alphabets have the same frequency, then the program must print the alphabet that is least in the alphabetical order. Boundary Condition(s): 2 <= Length of S <= 1000 1 <= Q <= 10^5 Example : Input: badbadbed 4 0 8 1 4 0 5 2 7 Output: b a a b #include <bits/stdc++.h> using namespace std; int main(int argc, char** argv) { string s; cin >> s; int k; cin >> k; int x, y; while (k--) { cin >> x >> y; map<char, int>counter; string ss = s.substr(x, y - x + 1); set <char>sample; for (auto i : ss) sample.insert(i); int maxx = -1, st; char anss; for (auto i : sample) if ((st = count(ss.begin(), ss.end(), i)) > maxx) { maxx = st; anss = i; } cout << anss << endl; } }
Following code has a lot of memory waste, but each query is looked up in O(1): int main() { std::string s; int q = 0, start = 0, end = 0; std::cin >> s; std::cin >> q; auto mem = std::make_unique<int[]>(26 * s.length()); for (int i = 0; i < s.length(); i++) { mem[i * 26 + s[i] - 'a']++; if (i < (s.length()-1)) { for (int l = 0; l < 26; l++) { mem[(i+1) * 26 + l] = mem[i * 26 + l]; } } } for (int i = 0; i < q; i++) { std::cin >> start >> end; int max_val = 0; int max_idx = -1; for (int l = 0; l < 26; l++) { auto v = (mem[end * 26 + l] - mem[start * 26 + l]); if (v > max_val) { max_val = v; max_idx = l; } } std::cout << (char)('a' + max_idx) << std::endl; } return 0; }
70,043,553
70,044,582
what is the difference between stl priority_queue and heap-related method?
I used heap-related operations to maintain a heap structure. For example: std::vector<int> a = {1,2,56, 2}; std::make_heap(a.begin(), a.end()); // add a.push_back(3); std::push_heap(a.begin(), a.end()); // erase std::pop_heap(a.begin(), a.end()); int v = a.back(); a.pop_back(); Recently, I find there is a structure named priority_queue seems also implement a heap. which has simpler function with push pop. Is there any difference between these two? (performance, memory, and other things) And which one you think is better? can i use reserve to reduce memory allocate time since the container is vector (for heap operation)?
See cppreference.com: Working with a priority_queue is similar to managing a heap in some random access container, with the benefit of not being able to accidentally invalidate the heap. And in case it isn't clear: your code manages a heap in a random access container.
70,043,576
70,043,608
Is this a function or variable definition in c++ code?
I am reading a piece of c++ code in which ids, curi and len are integer, content are string. I don't understand what's match_word() part. Is it a function or variable? I can't find its definition in all header files. if(-1!=ids) { len = ids - curi; string match_word(content, curi, len); bool rejudge = false; ... }
From std::string documentation string match_word(content, curi, len); This is/uses a substring constructor which Copies the portion of content that begins at the character position curi and spans len characters (or until the end of content, if either content is too short or if len is string::npos). So for example std::string s = "Hello World"; string match_word(s, 2, 7); std::cout<<match_word<<std::endl; //prints llo Wor The above will print llo Wor Now coming to your question: Is this a function or variable definition in c++ code? Basically this is a variable definition using the substring constructor. So in your case match_word is a variable of type std::string.
70,043,855
70,056,475
Are arguments of unary and binary operation arguments guaranteed to be same as original data if passed by reference?
As you know, we can provide UnaryOperation and BinaryOperation for a lot of stl functions. Arguments of these methods can be defined by value, but in a lot of cases, we pass them by reference as follows: Ret fun(const Type &a); // UnaryOperation Ret fun(const Type1 &a, const Type2 &b); // BinaryOperation Now I wonder if these callback arguments are guaranteed to be the same element as main data by standard or not. For example, is the following code valid in the standard? #include <iostream> #include <vector> #include <execution> #include <algorithm> int main() { std::vector<int> arr(10); std::transform(std::execution::par, arr.begin(), arr.end(), arr.begin(), [&arr](const int& v) -> int { return (&v - &arr[0]); }); for (const auto& v: arr) std::cout << v << " "; } Because (&v - &arr[0]) will be valid if and only if v refers to original elements in arr.
The example as written exhibits undefined behavior. Parallel algorithms are given a dispensation to make arbitrary copies of elements of the sequence, under certain circumstances. [algorithms.parallel.user]/1 Unless otherwise specified, function objects passed into parallel algorithms ... shall not ... rely on the identity of the provided objects. [algorithms.parallel.exec]/3 Unless otherwise stated, implementations may make arbitrary copies of elements (with type T) from sequences where is_trivially_copy_constructible_v<T> and is_trivially_destructible_v<T> are true. [Note: This implies that user-supplied function objects should not rely on object identity of arguments for such input sequences. Users for whom the object identity of the arguments to these function objects is important should consider using a wrapping iterator that returns a non-copied implementation object such as reference_wrapper<T> (20.14.5) or some equivalent solution. —end note] A strict reading of [algorithms.parallel.user]/1 suggests that the user-provided function must never rely on being given the original element and not a copy. The non-normative note in [algorithms.parallel.exec]/3 appears to suggest that it would be OK to so rely if the element type is not trivially copyable or destructible. In any case, the example uses int for element type, which is in fact trivially copyable and destructible, and for which the std::transform(par) implementation is clearly allowed to make copies. For motivation, see P0518r1 "Allowing copies as arguments to function objects given to parallel algorithms in response to CH11" Non-parallel algorithms, on the other hand, are not allowed to make copies of elements unless required by the algorithm's specification. Thus, for non-parallel std::transform, the user-provided function may indeed rely on being given a reference to the element of the source sequence. [res.on.data.races]/5 A C++ standard library function shall not access objects indirectly accessible via its arguments or via elements of its container arguments except by invoking functions required by its specification on those container elements. The specification of std::transform in [alg.transform] says that it should call op(*(first1 + (i - result))) for "every iterator i in the range [result, result + N)"; that is, it should pass the result of dereferencing the iterator into the source sequence directly to the user-provided function.
70,043,928
70,044,174
How to use pointer to string in cpp?
I am studying pointers in C++. I have studied call by value and call by reference concept. I am trying to create a function to reverse a string which accepts a pointer to string and the size of string. The code is as follow void reverse(string* str, int size) { int start = 0; int end = size - 1; while(start < end) { swap(*str[start++], *str[end--]); } } int main() { string str = "Something"; reverse(&str, str.length()); cout << "Reversed string: " << str << endl; return 0; } I am getting this error: error: no match for ‘operator*’ (operand type is ‘std::string’ {aka ‘std::__cxx11::basic_string’}) 12 | swap(*str[start++], *str[end--]); I don't want to use the character array, is there way to do it? Someone please explain, what's wrong in my code. Thank you.
Just need a little bit of change in your code Change this *str[start++] to (*str).at(start++) void reverse(string* str, int size) { int start = 0; int end = size - 1; while(start < end) { swap((*str).at(start++),(*str).at(end--)); } } int main() { string str = "Something"; reverse(&str, str.length()); cout << "Reversed string: " << str << endl; return 0; }
70,043,938
70,044,509
move ctor of std::string does not work properly?
Why the msg is not being modified after the call to std::move(msg)? int main() { std::string msg( "Error!" ); std::cout << "before try-catch: " << msg << '\n'; try { throw std::invalid_argument( std::move( msg ) ); } catch ( const std::invalid_argument& ia ) { std::cerr << ia.what( ) << '\n'; } std::cout << "after try-catch: " << msg << '\n'; // Here I expect to see an empty msg // like this: after try-catch: return 0; } I want to move msg to the ctor of std::invalid_argument instead of copying it. I thought that msg should be modified and be left in an unspecified but valid state after the call to std::move. But this happens: before try-catch: Error! Error! after try-catch: Error! Why is this happening? Is the move ctor of std::string not being called? Or is this some kind of aggressive compiler optimization despite using -O0 option?
Here, the only relevant constructor of std::invalid_argument is: invalid_argument(const std::string& what_arg); Const-ref parameter can bind to anything, including an xvalue, which std::move(msg) is. std::move() itself is just a cast, the real work of moving data out of a string could have been made inside a constructor. But you can't modify an xvalue taken by a const-ref. The only option you have is to make a copy, leaving msg unmodified. Cppreference has the following note, which explains the absence of a constructor taking std::string&&: Because copying std::invalid_argument is not permitted to throw exceptions, this message is typically stored internally as a separately-allocated reference-counted string. This is also why there is no constructor taking std::string&&: it would have to copy the content anyway.
70,044,161
70,044,193
C++ declaring a const function in header and implementing it in .cpp
I have the following header: #include <string> using namespace std; enum COLOR {Green, Blue, White, Black, Brown}; class Animal{ private: string _name; COLOR _color; public: Animal(); ~Animal(); void speak() const; void move() const; } ; And the following .cpp implementation: #include <iostream> #include <string> #include "Animal.h" Animal::Animal(): _name("unknown") { cout << "constructing Animal object" << endl; }; Animal::~Animal() { cout << "destructing Animal object" << endl; } void Animal::speak() { cout << "Animal speaks" << endl; } void Animal:: move(){}; However, the speak() and move() functions are giving me an error: "no declaration matches Animal::speak()" . If I remove the 'const' at the tail of the declaration, there are no issues in compilation. How do I correctly implement a const function in a .cpp file?
You forget to put const in the implementation. Change your code to: void Animal::speak() const { cout << "Animal speaks" << endl; } void Animal::move() const {};
70,044,479
70,078,050
How to configure pcapplusplus so it doesn't ignore packets which are greater than MTU size on PcapLiveDevice?
I am using pcapplusplus library for tcp packet processing in c++. When i am receiving packets greater than MTU size, which is 1500 bytes, my program stops further processing as TcpReassembly is not processing that packet. Due to this onMessageReadyCallback is not calling for that packet. And more serious, as that packet is being ignored by tcpReassembly, the corresponding sequence no, lets say x, of that packet is being ignored too. So my program is not able to process any other incoming packet as it expects a sequence no of x but tcpReassmbly had already ignored that packet so it is not going to receive packet of sequence no x and the program execution stops. So my question is do we have a way to direct tcpReassembly do not ignore packets greater than MTU size. Just forward it to respective function callback?
Basically the problem was with tcpreplay and not the pcpp::TcpReassembly. Tcpreplay can’t send packets which are larger than the MTU of the interface [https://tcpreplay.appneta.com/wiki/faq.html]. So Now lemme state where the problem was occuring. I had a pcap file and I was using tcpreplay to replay those packets on an interface. But tcpreplay doesn't replay jumbo packets. It simply ignored those packets. So when that packet is ignored, TcpReassembly was waiting for that sequence number, but it would never got that sequence number in future also because that sequence number was ignored already. Although next packets will come, but TcpReassembly doesn't go ahead without receiving that ignored sequence no packet. So program execution stopped, much like that the application hanged, but that's on tcpreplay end, not the TcpReassembly end. You need not worry about TcpReassembly, it will reassemble any packet that it would receive. There is not any limitation with MTU size. I checked the cpp file of TcpReassembly as well and there is no check that if packet size is greater than MTU size, then ignore packet.
70,044,902
70,045,194
C++ Sort rows of a 2D array, based on the first column using bubblesort
Disclaimer: These are all fake addresses it is just for learning purposes. I want my list to be sorted based of the first columns which are the [i][0] and with that make the rest of the row ([i][j]) follow with the new sorted position column. Right now my code seems to be ONLY sorting the first columns but not making the whole the row follow with it to the new position the first columns has been given. I've tried many ways but haven't been able to find a solution. Please help me! /* konst.txt includes following: Stengren Lena Bokstavsgatan 10 27890 Stadköping Osterblad Johan Grönskog 12A 10908 Ljushöjda Broholme Reny Havstundav 8 36799 Hökänget Roholm Karol Stugsten 7 45892 Rågskog Lindagren Erika Hjufjord 139 87834 Skogholma */ string adresser[50][6]; string input_file = "D:\\konst.txt"; ifstream input_stream; int lastpos = 0; string temp; input_stream.open(input_file); for (int i = 0; i < 20; i++) { for (int j = 0; j < 6; j++) { input_stream >> adresser[i][j]; //Saves the columns and rows in the 2d array cout << adresser[i][j] << ' '; //Writes out the whole list } cout << endl; } for (int i = 0; i < 50; i++) { //Finds the last position for columns if (adresser[i][0] == "") { lastpos = i; break; } } cout << "\n\n\n\n"; for (int i = lastpos - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (adresser[j][0] > adresser[j + 1][0]) { //Sorts the array for ONLY the first columns. temp = adresser[j][0]; adresser[j][0] = adresser[j + 1][0]; adresser[j][0] = temp; } } } Reminder of what the 2d array includes: /* Stengren Lena Bokstavsgatan 10 27890 Stadköping Osterblad Johan Grönskog 12A 10908 Ljushöjda Broholme Reny Havstundav 8 36799 Hökänget Roholm Karol Stugsten 7 45892 Rågskog Lindagren Erika Hjufjord 139 87834 Skogholma */ What the code does: /* Broholme Lena Bokstavsgatan 10 27890 Stadköping Lindagren Johan Grönskog 12A 10908 Ljushöjda Osterblad Reny Havstundav 8 36799 Hökänget Roholm Karol Stugsten 7 45892 Rågskog Stengren Erika Hjufjord 139 87834 Skogholma */ What I want it to do: /* Broholme Reny Havstundav 8 36799 Hökänget Lindagren Erika Hjufjord 139 87834 Skogholma Osterblad Johan Grönskog 12A 10908 Ljushöjda Roholm Karol Stugsten 7 45892 Rågskog Stengren Lena Bokstavsgatan 10 27890 Stadköping */
Arrays are not a good datatype to do what you are trying to do. It is good to take "words" from real life and use them in your code. What you are doing is sorting contacts, so make something that represents a contact first, e.g. a struct. From there build your code, (one function at a time, functions are great for naming things too) which then will become more readable and easier to understand. For example like this : #include <fstream> #include <functional> #include <iostream> #include <sstream> #include <string> #include <vector> #include <regex> struct contact_info_t { std::string first_name; std::string last_name; std::string address; std::string postal_code; std::string city; }; // removed the "special" characters for now, seems code has some trouble with that std::istringstream file_content { "Stengren Lena Bokstavsgatan 10 27890 Stadkoping\n" "Osterblad Johan Gronskog 12A 10908 Ljushojda\n" "Broholme Reny Havstundav 8 36799 Hokanget\n" "Roholm Karol Stugsten 7 45892 Ragskog\n" "Lindagren Erika Hjufjord 139 87834 Skogholma\n" }; // load uses a regex to split up string, I think that's what causes the issues with special characters. // but the bottom line is read your file and build a vector of structs from it. Not an array auto load(std::istream& file) { static const std::regex rx{ "(\\w+)\\s+(\\w+)\\s+(\\w+\\s\\w+)\\s+(\\w+)\\s+(.*)" }; std::smatch match; std::vector<contact_info_t> contacts; std::string line; while (std::getline(file,line)) { if (std::regex_search(line,match,rx)) { contact_info_t info; info.last_name = match[1]; info.first_name = match[2]; info.address = match[3]; info.postal_code = match[4]; info.city = match[5]; contacts.push_back(info); } } return contacts; } // Since you can sort by multiple predicates (functions that return a bool) // I made a generic sort function. It sorts pointers to the structs // so that no data is move where it is not necessary auto sort(const std::vector<contact_info_t>& contacts, std::function<bool(const contact_info_t* lhs, const contact_info_t* rhs)> predicate) { std::vector<const contact_info_t*> sorted_contacts; for (const auto& contact : contacts) sorted_contacts.push_back(&contact); std::sort(sorted_contacts.begin(), sorted_contacts.end(), predicate); return sorted_contacts; } // show the sorted contacts, one struct at a time. // that way it is impossible for columns to get mixed up void show_sorted_contacts(const std::vector<const contact_info_t*>& sorted_contacts) { for (const auto& contact : sorted_contacts) { std::cout << contact->last_name << " "; std::cout << contact->first_name << " "; std::cout << contact->address << " "; std::cout << contact->city << " "; std::cout << contact->postal_code << "\n"; } } int main() { auto contacts = load(file_content); auto contacts_sorted_by_last_name = sort(contacts, [](const contact_info_t* lhs, const contact_info_t* rhs) { return (lhs->last_name < rhs->last_name); }); show_sorted_contacts(contacts_sorted_by_last_name); }
70,045,775
70,046,486
Alignment attribute to force aligned load/store in auto-vectorization of GCC/CLang
It is known that GCC/CLang auto-vectorize loops well using SIMD instructions. Also it is known that there exist alignas() standard C++ attribute, which among other uses also allows to align stack variable, for example following code: Try it online! #include <cstdint> #include <iostream> int main() { alignas(1024) int x[3] = {1, 2, 3}; alignas(1024) int (&y)[3] = *(&x); std::cout << uint64_t(&x) % 1024 << " " << uint64_t(&x) % 16384 << std::endl; std::cout << uint64_t(&y) % 1024 << " " << uint64_t(&y) % 16384 << std::endl; } Outputs: 0 9216 0 9216 which means that both x and y are aligned on stack on 1024 bytes but not 16384 bytes. Lets now see another code: Try it online! #include <cstdint> void f(uint64_t * x, uint64_t * y) { for (int i = 0; i < 16; ++i) x[i] ^= y[i]; } if compiled with -std=c++20 -O3 -mavx512f attributes on GCC it produces following asm code (provided part of code): vmovdqu64 zmm1, ZMMWORD PTR [rdi] vpxorq zmm0, zmm1, ZMMWORD PTR [rsi] vmovdqu64 ZMMWORD PTR [rdi], zmm0 vmovdqu64 zmm0, ZMMWORD PTR [rsi+64] vpxorq zmm0, zmm0, ZMMWORD PTR [rdi+64] vmovdqu64 ZMMWORD PTR [rdi+64], zmm0 which two times does AVX-512 unaligned load + xor + unaligned store. So we can understand that our 64-bit array-xor operation was auto-vectorized by GCC to use AVX-512 registers, and loop was unrolled too. My question is how to tell GCC that provided to function pointers x and y are both aligned to 64 bytes, so that instead of unaligned load (vmovdqu64) like in code above, I can force GCC to use aligned load (vmovdqa64). It is known that aligned load/store can be considerably faster. My first try to force GCC to do aligned load/store was through following code: Try it online! #include <cstdint> void g(uint64_t (&x_)[16], uint64_t const (&y_)[16]) { alignas(64) uint64_t (&x)[16] = x_; alignas(64) uint64_t const (&y)[16] = y_; for (int i = 0; i < 16; ++i) x[i] ^= y[i]; } but this code still produces unaligned load (vmovdqu64) same as in asm code above (of previous code snippet). Hence this alignas(64) hint doesn't give anything useful to improve GCC assembly code. My Question is how do I force GCC to make aligned auto-vectorization, except for manually writing SIMD intrinsics for all operations like _mm512_load_epi64()? If possible I need solutions for all of GCC/CLang/MSVC.
Though not entirely portable for all compilers, __builtin_assume_aligned will tell GCC to assume the pointer are aligned. I often use a different strategy that is more portable using a helper struct: template<size_t Bits> struct alignas(Bits/8) uint64_block_t { static const size_t bits = Bits; static const size_t size = bits/64; std::array<uint64_t,size> v; uint64_block_t& operator&=(const uint64_block_t& v2) { for (size_t i = 0; i < size; ++i) v[i] &= v2.v[i]; return *this; } uint64_block_t& operator^=(const uint64_block_t& v2) { for (size_t i = 0; i < size; ++i) v[i] ^= v2.v[i]; return *this; } uint64_block_t& operator|=(const uint64_block_t& v2) { for (size_t i = 0; i < size; ++i) v[i] |= v2.v[i]; return *this; } uint64_block_t operator&(const uint64_block_t& v2) const { uint64_block_t tmp(*this); return tmp &= v2; } uint64_block_t operator^(const uint64_block_t& v2) const { uint64_block_t tmp(*this); return tmp ^= v2; } uint64_block_t operator|(const uint64_block_t& v2) const { uint64_block_t tmp(*this); return tmp |= v2; } uint64_block_t operator~() const { uint64_block_t tmp; for (size_t i = 0; i < size; ++i) tmp.v[i] = ~v[i]; return tmp; } bool operator==(const uint64_block_t& v2) const { for (size_t i = 0; i < size; ++i) if (v[i] != v2.v[i]) return false; return true; } bool operator!=(const uint64_block_t& v2) const { for (size_t i = 0; i < size; ++i) if (v[i] != v2.v[i]) return true; return false; } bool get_bit(size_t c) const { return (v[c/64]>>(c%64))&1; } void set_bit(size_t c) { v[c/64] |= uint64_t(1)<<(c%64); } void flip_bit(size_t c) { v[c/64] ^= uint64_t(1)<<(c%64); } void clear_bit(size_t c) { v[c/64] &= ~(uint64_t(1)<<(c%64)); } void set_bit(size_t c, bool b) { v[c/64] &= ~(uint64_t(1)<<(c%64)); v[c/64] |= uint64_t(b ? 1 : 0)<<(c%64); } size_t hammingweight() const { size_t w = 0; for (size_t i = 0; i < size; ++i) w += mccl::hammingweight(v[i]); return w; } bool parity() const { uint64_t x = 0; for (size_t i = 0; i < size; ++i) x ^= v[i]; return mccl::hammingweight(x)%2; } }; and then convert the pointer to uint64_t to a pointer to this struct using reinterpret_cast. Converting a loop over uint64_t into a loop over these blocks typically auto vectorize very well.
70,045,994
70,046,031
Why, when I use a pointer to pass an array to a function, the array's length appears to be 1?
I'm trying to pass an array as a pointer to a function, but when I do that the function only sees the pointer as an array with 1 variable. Here is my code: void make3(int* a) { int n = sizeof(a) / sizeof(a[0]); for (int i = 0; i < n; i++) {a[i] = 3;} } int main() { int a[3] = { 0, 1, 2 }; make3(a); int* b = a; for (int i = 0; i < sizeof(a)/sizeof(a[0]); i++) { cout << *(b + i) << endl; } } The function make3 only changes the first value of the array to 3, instead of all of them. Is this normal? If not, what am I doing wrong?
When you pass an array to a function, it decays to a pointer. int n = sizeof(a) / sizeof(a[0]); Gets evaluated to int n = sizeof(int*) / sizeof(int); Which is 1 (when sizeof(int*) is 4 - depends on inplementation). You should pass the array size as an argument instead: void make3(int* a, int n) { for (int i = 0; i < n; i++) {a[i] = 3;} } int main() { int a[3] = { 0, 1, 2 }; make3(a, 3); for (int i = 0; i < 3; i++) { cout << a[i] << endl; } } If you can’t add that argument, use std::vector: #include <vector> void make3(std::vector<int> &a) { for (int i = 0; i < a.size(); i++) {a[i] = 3;} } int main() { std::vector<int> a{ 0, 1, 2 }; make3(a); for (int i = 0; i < a.size(); i++) { cout << a[i] << endl; } }
70,046,617
70,046,766
Nested designated initializers
Does C++ 20 allows nested designated initializers? E.g: struct Outer { int32_t counter; struct { std::string name; } inner; struct { std::optional<int32_t> value; } inner_optional; }; Outer outer = { .counter = 100, .inner = { .name = "test" // nested } }; If this is allowed, can someone provide a link to a trusted source? I can't find it on cppreference.
Yes, this is supported, cppreference - aggregate initialization states: If the initializer clause is a nested braced-init-list (which is not an expression), the corresponding array element/class member/public base (since C++17) is list-initialized from that clause: aggregate initialization is recursive. List initialization is aggregate initialization for aggregates. Note that truly nested C designated initializers, i.e doing outer = {.inner.name = ""};, are not supported in C++. The required workaround is exactly what you have wrote.
70,046,738
70,050,602
C++ Exception "Access violation reading location"
#include <iostream> #include <fstream> using namespace std; struct review { string text; string date; }; void getRegistry(int i) { review* reg = new review; ifstream file; file.open("test.txt", ios::binary); if (file) { file.seekg(i * sizeof(review), ios::beg); file.read(reinterpret_cast<char*>(reg), sizeof(review)); cout << reg->text; file.close(); } delete reg; } void generateBinary() { ofstream arq("test.txt", ios::binary); review x; x.text = "asdasdasd"; x.date = "qweqweqwe"; for (int i = 1; i <= 1000000; i++) { arq.write(reinterpret_cast<const char*>(&x), sizeof(review)); } arq.close(); } int main() { generateBinary(); getRegistry(2); return 0; } Hello, I'm trying to make a program which writes several "reviews" to a binary file, then reads a certain registry. The program seems to work, but, in the end, it always throws an exception: "Exception thrown at 0x00007FF628E58C95 in trabalho.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF." How can I solve this? Thank you!
The problem is that you can't read/write std::string objects they way you are. std::string holds a pointer to variable-length character data that is stored elsewhere in memory. Your code is not accounting for that fact. To be able to seek to a specific object in a file of objects the way you are attempting, you have to use fixed-sized objects, eg: #include <iostream> #include <fstream> #include <cstring> using namespace std; struct review { char text[12]; char date[12]; }; void getRegistry(int i) { ifstream file("test.txt", ios::binary); if (file) { if (!file.seekg(i * sizeof(review), ios::beg)) throw ...; review reg; if (!file.read(reinterpret_cast<char*>(&reg), sizeof(reg))) throw ...; cout << reg.text; } } void generateBinary() { ofstream arq("test.txt", ios::binary); review x = {}; strncpy(x.text, "asdasdasd", sizeof(x.text)-1); strncpy(x.date, "qweqweqwe", sizeof(x.date)-1); for (int i = 1; i <= 1000000; ++i) { if (!arq.write(reinterpret_cast<char*>(&x), sizeof(x))) throw ...; } } int main() { generateBinary(); getRegistry(2); return 0; } Otherwise, to deal with variable-length data, you need to (de)serialize each object instead, eg: #include <iostream> #include <fstream> #include <cstdint> using namespace std; struct review { string text; string date; }; string readStr(istream &is) { string s; uint32_t len; if (!is.read(reinterpret_cast<char*>(&len), sizeof(len))) throw ...; if (len > 0) { s.resize(len); if (!is.read(s.data(), len)) throw ...; } return s; } void skipStr(istream &is) { uint32_t len; if (!is.read(reinterpret_cast<char*>(&len), sizeof(len))) throw ...; if (len > 0) { if (!is.ignore(len)) throw ...; } } void writeStr(ostream &os, const string &s) { uint32_t len = s.size(); if (!os.write(reinterpret_cast<char*>(&len), sizeof(len)) throw ...; if (!os.write(s.c_str(), len)) throw ...; } review readReview(istream &is) { review r; r.text = readStr(is); r.date = readStr(is); return r; } void skipReview(istream &is) { skipStr(is); skipStr(is); } void writeReview(ostream &os, const review &r) { writeStr(is, r.text); writeStr(is, r.date); } void getRegistry(int i) { ifstream file("test.txt", ios::binary); if (file) { while (i--) skipReview(file); review reg = readReview(file); cout << reg.text; } } void generateBinary() { ofstream arq("test.txt", ios::binary); review x; x.text = "asdasdasd"; x.date = "qweqweqwe"; for (int i = 1; i <= 1000000; ++i) { writeReview(arq, x); } } int main() { generateBinary(); getRegistry(2); return 0; }
70,046,749
70,047,438
Why do i get QJsonValue(undefined)?
When I make request to API to get bid price, I'm getting QJsonValue undefined, and cannot display it later, what am i doing wrong? { QApplication a(argc, argv); MainWindow w; w.show(); QNetworkAccessManager m_manager; // make request QNetworkRequest request = QNetworkRequest(QUrl("https://api.30.bossa.pl/API/GPW/v2/Q/C/_cat_name/WIG20?_t=1637005413888")); QNetworkReply* reply = m_manager.get(request); QObject::connect(reply, &QNetworkReply::finished, [reply]() { QByteArray rawData = reply->readAll(); QString textData(rawData); qDebug() << textData; QJsonDocument doc = QJsonDocument::fromJson(textData.toUtf8()); QJsonObject obj = doc.object(); qDebug() << obj; QJsonValue value = obj.value(QString("_quote_min")); qDebug() << obj.value(QString("_quote_min"));; qDebug() << "Bid value is" << value.toString();; reply->deleteLater(); // make sure to clean up }); return a.exec(); } this is my json: QJsonObject({"_count":1,"_d":[{"_h":"Własne - 19 listopada 2021 17:15","_hs":"Własne","_max_quote_dtm":"19 listopada 2021","_max_quote_dtm_lc":"19 listopada, 17:15","_ret_quote_dtm":"2021-11-19","_t":[{"_30d_change_max":2453.57,"_30d_change_min":2221.68,"_ask_orders_nr":null,"_ask_size":null,"_ask_volume":null,"_bid_orders_nr":null,"_bid_size":null,"_bid_volume":null,"_change":"-1.02","_change_close_open":"-1.04","_change_max_min":"+2.91","_change_pnts":-23.13,"_change_proc":-1.02,"_change_settl_ref":null,"_change_suffix":"%","_change_type":"_change_proc","_debut":"0","_group":"X1","_is_indice":"1","_isin":"PL9999999987","_live":"0","_open_positions":null,"_phase":"Zamknięcie ostateczne","_quote":"2248.18","_quote_date":"2021.11.19","_quote_imp":"2276.90","_quote_max":"2286.37","_quote_min":"2221.68","_quote_open":"2271.91","_quote_ref":"2271.31","_quote_time":"17:15","_quote_type":"_quote","_quote_volume":null,"_settlement_price":null,"_step":"2","_sw_symbol_short":0,"_symbol":"WIG20","_symbol_short":"WIG20","_time":"17:15","_transactions_nr":null,"_turnover_value":1257698337,"_type_of_instrument":"0","_volume":null}]}],"_d_fx":{"_h":null,"_hs":null,"_max_quote_dtm":null,"_max_quote_dtm_lc":null,"_t":[]},"_i":[null],"_quote_date":null,"_symbol":["WIG20"],"_type":"C","message":"OK"})
If you're confident that the JSON structure will always be the same, then you can find your value like the following. (I broke it down into multiple objects and named them the same way they are named in your JSON file.) QJsonDocument doc = QJsonDocument::fromJson(textData.toUtf8()); auto rootObj = doc.object(); auto _d = rootObj.value("_d").toArray(); auto _t = _d[0].toObject().value("_t").toArray(); auto _quote_min = _t[0].toObject().value("_quote_min"); qDebug() << _quote_min; Output: QJsonValue(string, "2221.68")
70,046,896
70,046,938
Use Functor / Predicate to find the first element smaller than its predecessor in vector
currently I am trying to use function objects to find the first element that is smaller than the previous element in a vector. For example I have vector v and its contents are { 25, 30, 10, 40}; I tried toying with functors and with the algorithm library, but I can't get a correct result. My attempt was: auto target = find_if( v.begin( ), v.end( ), &greaterneighbour ); if ( target != v.end( ) ) cout << target << endl; The functor I tried to implement however was incorrect and only worked with pre-set elements (like comparing each element with 4). My question is how can I use functors to compare two elements of a vector.
You can use std::adjacent_find() for that. auto iter = std::adjacent_find(begin(v), end(v), [](const auto& a, const auto& b) { return a < b; });
70,047,118
70,047,167
no matching function call to error in vector.push_back
I am getting the following error while compiling my C++ program: error: no matching function for call to 'std::vector<ChainingTable<int>::Record, std::allocator<ChainingTable<int>::Record> >::push_back(ChainingTable<int>::Record*)' 324 | vector_.push_back(new Record(key, value)); The error is coming from the line: template <class TYPE> bool ChainingTable<TYPE>::update(const std::string &key, const TYPE &value) { if (!keyExists) { vector_.push_back(new Record(key, value)); } } This is defined for the class: class ChainingTable : public Table<TYPE> { struct Record { TYPE data_; std::string key_; Record(const std::string &key, const TYPE &data) { key_ = key; data_ = data; } }; std::vector<std::vector<Record>> records_; int capacity_; // capacity of the array Complete code: int sz = numRecords(); bool rc = true; std::hash<std::string> hashFunction; size_t hash = hashFunction(key); size_t idx = hash % capacity_; std::vector<Record> vector_ = records_[idx]; bool keyExists = false; for (int i = 0; i < vector_.size(); i++) { if (vector_[i].key_ == key) { vector_[i].data_ = value; keyExists = true; } } if (!keyExists) { vector_.push_back(new Record(key, value)); } What could be the reason for this?
Your vector is declared to store objects of type Record, not pointers to them (Record *) but you are trying to push result of operator new which returns Record *, just use std::vector::emplace_back instead: vector_.emplace_back(key, value); Note: in this line std::vector<Record> vector_ = records_[idx]; you create a copy and later modify it, seems that you need a reference. Note2: in your search loop you do not terminate even if you find object already, you should add break into if statement, that will make it more effective.
70,047,234
70,047,454
C++ breaks out of the loop when filling the array
So basically I am trying to create a loop that fills a matrix with random numbers. I need to make it so every column has a different range, unique to it. //Variables int lsx = 3; int lsy = 10; int lust[lsy][lsx]; int i = 0; int l = 0; int shpp = 7; //List setup for (i = 0; i < lsy; i++) { for (l = 0; l < lsx; l++) { lust[i][l] = 0; } } while (true) { //List generator for (i = 0; i < lsy; i++) { for (l = 0; l < lsx; l++) { //Column 1 if (i == 0) { lust[i][l] = rand() % flx; cout << lust[i][l] << '\n'; } //Column 2 if (i == 1) { lust[i][l] = rand() % fly; cout << lust[i][l] << '\n'; } //Column 3 if (i == 2) { lust[i][l] = rand() % shpp; cout << lust[i][l] << '\n'; } } cout << "Endline reached! \n \n"; } for (i = 0; i < lsy; i++) { for (l = 0; l < lsx; l++) { cout << lust[i][l] << " "; } cout << "\n"; } } } This only generates 3 lines. Does anyone have any ideas on why this could happen? I tried changing some stuff around but only got weirder results that wouldn't fill the array in completely eitherThis is what the program displays when I try and run it
for (l = 0; l < lsx; l++) { Column 1 if (i == 0) } lust[i][l] = rand() % flx; cout << lust[i][l] << '\n'; } Column 2 if (i == 1) } lust[i][l] = rand() % fly; cout << lust[i][l] << '\n'; } Column 3 if (i == 2) { lust[i][l] = rand() % shpp; cout << lust[i][l] << '\n'; } } cout << "Endline reached! \n \n"; You're using i (the line iterator) to evaluate what you're going to fill. Which means your code will only concern itself with lines 0, 1 and 2. Instead, shift that i to l - your column iterator. It should work. Also, consider removing the while true loop. Not only is it redundant, it's also pretty dangerous considering there's no break condition - in this case it's safe, since you'll be around to shut it down, but as a good practice stay out of while(true) unless you can't write your break condition as a boolean expression
70,047,306
70,047,507
Clear vertex of all neighbors of v
I'm implementing an algorithm in C++ with Boost Graph. I want to find all the vertex in the neighborhood of v (so, all its neighbors), then change a property of their and finally clear all of their edges. I found in Boost the function adjacent_vertices(v,g) (where v is the vertex and g is the graph) to find all the neighbors. Then I want to apply on all of them the function clear_vertex(v,g) (again, v is the vertex and g is the graph) to remove all of their edges. At this point, I have a problem. The adjacent_vertices function returns a pair of adjacency_iterator, while for the clear_vertex function I need vertex_iterator (if I understand correctly how these functions work). So, there is an easy way to transform the adjacency_iterator in vertex_iterator? If I keep the adjacency_iterator and pass it to the clear_vertex function, the problem is that it doesn't remove the edges (or remove them randomly to some vertices). My wrong code is: Graph::adjacency_iterator v,vend; for(boost::tie(v,vend) = neighbours; v != vend ; ++v) { clear_vertex(*v,g2); }
It depends on the edge container selectors. The easiest way is when the containers are node-based, i.e. only the iterators/descriptors to any removed edges are invalidated. Another way is when you split the "query" and "modification" aspects, e.g. Compiler Explorer #include <boost/graph/adjacency_list.hpp> #include <boost/graph/random.hpp> #include <random> void clear_all_neighbours(auto v, auto& g) { auto neigh = adjacent_vertices(v, g); std::set to_clear(neigh.first, neigh.second); for (auto u : to_clear) clear_vertex(u, g); } int main() { std::mt19937 prng(std::random_device{}()); boost::adjacency_list<> g; generate_random_graph(g, 1000,2000, prng); std::cout << "Before: " << num_edges(g) << "\n"; auto v = vertex(prng() % num_vertices(g), g); clear_all_neighbours(v, g); std::cout << "After: " << num_edges(g) << "\n"; } Possible output: Before: 2000 After: 1983
70,047,349
70,047,406
How to locate and remove these symbols from my reversed string
This is an oddly specific problem but I need help because I am very confused. I am trying to use pointers to ask a user to input a string and the output will print the reverse. So far I have used a reverse function and applied the pointers. Here's what the code looks like right now: #include <iostream> using namespace std; void reverse(char name[]) { char *p; p = name; while (*p != '\0') { ++p; } while (*p >= 0) { cout << *p; --p; } } int main() { char name[100]; cout << "Please enter a string: "; cin.getline(name, sizeof(name)); cout << "The reverse of the string is: "; reverse(name); return 0; } When I run the program, it works but there is one problem. For example the inputted string is Stack Overflow, this is the result: Please enter a string: Stack Overflow The reverse of the string is: wolfrevO kcatS ►☺ ◄ a As you can see there are these symbols that show up in the final output. I have tried locating where it comes from and I think it is because of the pointers because when I used an array for the function, it properly printed the reversed string without the symbols. I am asking if there is a way for me to remove these symbols while still using pointers? I have tried multiple variations on making the function with the pointers but the symbols still print at the end.
That garbarge happens because you don't have null terminating character at the beginning of the string, thus you don't terminate when going backwards. I modified your code to keep sentinel zero character at 0-th position, and now your code works without bugs. Also condition while (*p >= 0) should be replaced with while (*p). Try it online! #include <iostream> using namespace std; void reverse(char name[]) { char *p; p = name; while (*p != '\0') { ++p; } --p; while (*p) { cout << *p; --p; } } int main() { char name[100]; name[0] = 0; cout << "Please enter a string: "; cin.getline(name + 1, sizeof(name) - 1); cout << "The reverse of the string is: "; reverse(name + 1); return 0; } Input: Please enter a string: Stack Overflow Output: The reverse of the string is: wolfrevO kcatS
70,047,533
70,047,726
Why does my nested loop not check the second element of vector (empty string)?
I'm a bit stuck on this one.. my code should stop capitalising the characters when it hits the first empty string ( text[1] ).. but when I put a breakpoint in and step forward; the third string is considered straight after the first. The second element is ignored. The exercise is to print all strings but only capitalise the first one. #include <vector> int main() { std::vector<std::string> text = { "One, two, three-four-five. Once I caught a fish alive.", "", "Six, seven, eight-nine-ten. Then I let it go again.", "", "Why did I let it go? Because he bit my finger so.", "", "Which finger did he bite? This little finger on my right!"}; for (auto it = text.begin(); it != text.end(); ++it) { for (auto it2 = it->begin(); it2 != it->end() && !it->empty(); ++it2) { //empty string in text[2] never satisfies second condition *it2 = toupper(*it2); } std::cout << *it << std::endl; }; } Any ideas why? Thanks.
If I understood right, you want to stop capitalizing after the first empty string, and not after the first empty character, something like: ONE, TWO, THREE-FOUR-FIVE. ONCE I CAUGHT A FISH ALIVE. Six, seven, eight-nine-ten. Then I let it go again. Why did I let it go? Because he bit my finger so. Which finger did he bite? This little finger on my right! That could be done with only one loop and transforming the whole string: int main() { std::vector<std::string> text { "One, two, three-four-five. Once I caught a fish alive.", "", "Six, seven, eight-nine-ten. Then I let it go again.", "", "Why did I let it go? Because he bit my finger so.", "", "Which finger did he bite? This little finger on my right!"}; for (auto it = text.begin(); it != text.end() && !it->empty(); ++it) { std::transform(it->begin(), it->end(),it->begin(), ::toupper); }; for (auto const& str : text) { std::cout << str << std::endl; } } NOTE: As @user4581301 has pointed out, bear in mind that negative values (like extended ASCII) yield UB and you should decide what to do (i.e., casting via [](unsigned char c){ return std::toupper(c); } as suggested in the comments).
70,048,200
70,048,488
Difference between Generic Lambdas
I'm currently learning about generic lambda functions, and I am quite curious about the differences between: [](auto x){}; and []<typename T>(T x){}; They both do the same thing but is one faster than the other? What's the point of having these 2 syntaxes.
Although the two are functionally equivalent, they are the features of C++14 and C++20, namely generic lambda and template syntax for generic lambdas, which means that the latter is only well-formed in C++20. Compared to the auto which can accept any type, the latter can make lambda accept a specific type, for example: []<class T>(const std::vector<T>& x){}; In addition, it also enables lambda to forward parameters in a more natural form: []<class... Args>(Args&&... args) { return f(std::forward<Args>(args)...); }; You can get more details through the original paper P0428.
70,048,276
70,048,356
C++14 Static class map initialization
right now I'm creating a static class (yes, c++ does not have static classes, but to my knowledge creating a class with a private constructor gives the same result) like the following returning to me a map: class Foo() { public: static std::map<MyEnum, SomeInfo> getMap() { static const std::map<MyEnum, SomeInfo> fooMap { {MyEnum::Enum1, SomeInfo{ "info1", "Info 1" }}, {MyEnum::Enum2, SomeInfo{ "info2", "Info 2" }}, } return fooMap; } } struct SomeInfo { std::string id; std::string name; } This method may very frequently, in my opinion this doesn't look very efficient because everytime create a new istance of a map then return it. I've tried to create a static const std::map instead and initialize it in the following way: class Foo() { public: static const std::map<MyEnum, SomeInfo> fooMap { {MyEnum::Enum1, SomeInfo{ "info1", "Info 1" }}, {MyEnum::Enum2, SomeInfo{ "info2", "Info 2" }}, } } but this returns the following error: Static data member of type 'const std::map<MyEnum, SomeInfo>' must be initialized out of line I've really no idea how to do that, after some research I didn't find anything really helpful.. Any guesses? Thanks in advance to everyone!
You need to "define" your map after you "declared" it: See: https://en.cppreference.com/w/cpp/language/static #include <map> #include <string> struct SomeInfo { std::string id; std::string name; }; enum MyEnum { Enum1, Enum2 }; class Foo { private: static const std::map<MyEnum, SomeInfo> fooMap; public: static std::map<MyEnum, SomeInfo> getMap() { return fooMap; } }; const std::map<MyEnum, SomeInfo> Foo::fooMap = { {MyEnum::Enum1, SomeInfo{ "info1", "Info 1" }}, {MyEnum::Enum2, SomeInfo{ "info2", "Info 2" }} }; int main(){ auto val = Foo::getMap()[MyEnum::Enum1]; return 0; } And if you want to make your type not constructable you can delete the compiler generated default constructor via Foo() = delete; - it must not be private.
70,048,901
70,049,325
Arrays of Objects without standard constructor using Parameter Packs
I want to fill an std::array of size N with objects without a standard constructor. std::array<non_std_con,N> myArray; (It's std::array<kissfft<float>, 64> in my case, to be specific) This results in the error error: use of deleted function ... standard constructor Setup You can fill the array using an intializer list: std::array<non_std_con,N> myArray{non_std_con{init1,init2},non_std_con{init1,init2},...} The initializer list needs N objects. And you can build an array using parameter packs: template <class... Params> auto constexpr build_array(Params... params) { std::array<non_std_con, sizeof...(params)> myArray= {params...}; return myArray; } Question Is there a way to use this the other way around and build a parameter pack out of a single argument: std::array<non_std_con,N> buildArray(inti1,init2); This would build an array of N non_std_con where every object is initialized with {init1,init2} Thank you for your time
You could write: #include <array> #include <utility> #include <iostream> namespace detail { template < typename T, std::size_t ... Is > constexpr std::array<T, sizeof...(Is)> create_array(T value, std::index_sequence<Is...>) { // cast Is to void to remove the warning: unused value return {{(static_cast<void>(Is), value)...}}; } } template< typename T, int N, typename... CtorAgrs > constexpr std::array<T, N> buildArray(CtorAgrs... args) { using Array = std::array<T, N>; return detail::create_array<T>(T{args...}, std::make_index_sequence<N>()); } struct Foo{ int a, b; constexpr Foo(int a, int b) : a(a), b(b) { } }; int main() { constexpr auto array = buildArray<Foo, 10>(1, 2); for(const auto& f : array){ std::cout << f.a; std::cout << "\n"; } } or with C++-20 simply: template< typename T, int N, typename... CtorAgrs > constexpr std::array<T, N> buildArray(CtorAgrs&&... args) { auto doBuildArray = [&]<std::size_t ... Is>(std::index_sequence<Is...>) -> std::array<T, N> { // cast Is to void to remove the warning: unused value return {{(static_cast<void>(Is), T{args...})...}}; }; return doBuildArray(std::make_index_sequence<N>()); }
70,048,927
70,049,012
Why I am getting error while concatenating variables in output in C++?
I am trying to concatenate output variables in C++ In my code there are some calculations and when I am printing the output of the variables I am getting error. My code: #include<iostream> #include<string> #include<math.h> using namespace std; int main() { string name; cout<<"Enter the name of the borrower: "; cin>>name; float mortage_blanace; cout<<"Enter the mortage balance: "; cin>>mortage_blanace; float interest_rate; cout<<"Enter the annual interest rate: "; cin>>interest_rate; float current_monthly_payment; cout<<"Enter the current monthly payment: "; cin>>current_monthly_payment; float extra_monthly_payment; cout<<"Enter the extra monthly payment: "; cin>>extra_monthly_payment; cout<<"\n"; int new_payment = current_monthly_payment+extra_monthly_payment; float i = (interest_rate/100)/12; int current_duration_in_months = (log(current_monthly_payment/(current_monthly_payment/i)-mortage_blanace))/(log(1+i)); int new_duration_in_months = (log(new_payment/(new_payment/i)-mortage_blanace))/(log(1+i)); float current_interest = (current_monthly_payment*new_duration_in_months)-mortage_blanace; float new_interest = (new_payment*new_duration_in_months)-mortage_blanace; int current_duration_years = current_duration_in_months/12; int current_duration_months = current_duration_in_months%12; int new_duration_years = new_duration_in_months/12; int new_duration_months = new_duration_in_months%12; float savings = current_interest-new_interest; string fees; cout<<mortage_blanace + " " + mortage_blanace; cout<<"\n"; } return 0; } But I am getting following error: Untitled1.cpp: In function 'int main()': Untitled1.cpp:58:30: error: invalid operands of types 'float' and 'const char [7]' to binary 'operator+' cout<<mortage_blanace + " " + mortage_blanace; How can I get concatenated output in C++ like the one I want?! Any help is appreciated.
You can use the insertion operator (<<) to display values to standard output instead of trying to concatenate a float with an array of characters. cout << mortage_blanace << " " << mortage_blanace << endl;
70,049,327
70,049,507
How to read command line arguments from a text file?
I have a program that takes in one integer and two strings from a text file "./myprog < text.txt" but I want it to be able to do this using command line arguments without the "<", like "./myprog text.txt" where the text file has 3 input values. 3 <- integer AAAAAA <- string1 AAAAAA <- string2
If the reading of the parameters must be done solely from the file having it's name, the idiomatic way is, I would say, to use getline(). std::ifstream ifs("text.txt"); if (!ifs) std::cerr << "couldn't open text.txt for reading\n"; std::string line; std::getline(ifs, line); int integer = std::stoi(line); std::getline(ifs, line); std::string string1 = line; std::getline(ifs, line); std::string string2 = line; Because there are little lines in your file, we can allow ourselves some repetition. But as it becomes larger, you might need to read them into a vector: std::vector<std::string> arguments; std::string line; while (getline(ifs, line)) arguments.push_back(line); There some optimizations possible, as reusing the line buffer in the first example and using std::move(), but they are omitted for clarity.
70,049,647
70,050,377
Why is it not recommended to use a heap to sort a LinkedList?
I know how to sort a linked list using merge sort. The question is, why don't we just use a heap to create a sorted LinkedList? Traverse the linked list and keep adding items to a min-heap. Keep taking the items out of the heap and heapify the heap and add to a new result LinkedList. step one will have O(n) for traversing the list and O(nlogn) for adding items to the heap. Total O(nlogn) [Correct me if I am wrong]. Getting an item out of heap is O(1) adding an item as the next node in a LinkedList is O(1). [Correct me if this is wrong]. So the sort can be done in O(nlogn) if my understanding is correct. This is the same as the merge sort. In terms of memory, we are using an extra heap so total memory can be O(nlogn) I assume. Merge sort can also take O(nlogn) but can be improved to O(logn). The heap logic is the same as the "merging k sorted linked list". I am assuming each linked list has 1 item. I might be completely wrong about my complexities on the heap version. If someone knows the exact reason why heap should not be[Why merge sort is better] used, please explain. This is not heap sort and this is not an in-place algorithm. If the time complexity is O(n²logn), I am not sure how.
I know how to sort a linked list using merge sort. The question is, why don't we just use a heap to create a sorted LinkedList? Traverse the linked list and keep adding items to a min-heap. Keep taking the items out of the heap and heapify the heap and add to a new result LinkedList. Several reasons, among them: Asymptotic complexity is not the end of the story. Merge sort is especially clean and efficient to implement for linked lists, so it is among the best performing of the O(n log n) linked-list sorts. But asymptotic complexity is still part of the story. Heap sort of an array can be done with O(1) auxiliary space by using relationships among array indices to provide an implicit representation of the tree. This supports sorting in O(n log n) steps overall because accessing an array by index is O(1), but the same is not true of a linked list. To get an O(n log n) heap sort of a linked list, you have to build the heap as an actual tree or as an array, which requires O(n) overhead. And then it's a bit strained to call it a linked-list sort, because you could have done exactly the same thing with an array, or many other data structures. Also, merge sort can easily be made stable, but that's harder for heap sort and it probably requires additional overhead. So the sort can be done in O(nlogn) if my understanding is correct. Sure, any data set that can be enumerated in O(n) steps can be loaded into an array and sorted via any applicable O(n log n) array-sorting algorithm in O(n log n) steps. In the particular case of a linked list, one can also reform the nodes into a sorted list without increasing the asymptotic complexity. This is the same as the merge sort. The same asymptotic complexity does not mean the same performance. A large difference in the constant factor can still make an important difference. Plus, even if all else were equal, the much simpler code of linked-list merge sort vs what you describe is an enormous engineering advantage. It means faster development and fewer bugs. In terms of memory, we are using an extra heap so total memory can be O(nlogn) I assume. Merge sort can also take O(nlogn) but can be improved to O(logn). I have no idea where your O(n log n) idea comes from for either case. I count O(n) overhead for an auxiliary array in the heap sort case. On arrays, typical merge sort implementations have O(n) overhead, but on linked lists, O(log n) overhead is natural for merge sort. Regarding this comment: In a book, I saw we won't be able to sort a singly linked list with quick sort or heap sort. That book was wrong, even if we disallow reading the linked list out into an auxiliary array or other data structure on which to perform the actual sorting. If you do disallow such an auxiliary structure then I don't think you can do heap sort on a singly-linked list in less than o(n2 log n) steps, but you can do it. And you don't need fast random access or bi-directional traversal to perform an O(n log n) quick sort.
70,049,958
70,489,827
Exception thrown at ispunct() when reading words from a text file - C++
Trying to create a program that reads words from a text file and outputs 20 password combinations with 4 words in each and with certain conditions such as no punctuation in word, no digits, and no characters other than the first may be uppercase. However, I am getting an exception thrown at ispunct(b[i]) and I think it has to do with the changing sizes of the words but I am not sure. Any help would be appreciated as my knowledge with C++ is rudimentary at best. #include <iostream> #include <fstream> #include <vector> using namespace std; bool acceptWord(string a, string b) { if (b.length() > 3) { for (int i = b.length() - 1; i; --i) { if (ispunct(b[i])) { return false; } if (isdigit(b[i])) { return false; } } if (isalpha(b[0]) && isupper(b[0])) { for (int i = b.length(); i; --i) { if (isupper(b[i])) { return false; } } } a = b; return true; } else { return false; } } int main() { fstream file; string word, filename; vector<string> tokens; int random = rand() % 81; filename = "input.txt"; file.open(filename.c_str()); if (!file.is_open()) { cout << "File not found" << endl; exit(1); } while (file >> word) { string token = ""; if (acceptWord(token, word)) { for (int i = 0; i < 80; ++i) { tokens[i] = token; } } for (int i = 0; i < 20; ++i) { cout << tokens[random] + " " + tokens[random] + " " + tokens[random] + " " + tokens[random] + "1" << endl; } } return 0; }
There are a number of fundamental errors in your code (and your reasoning) that make it seem like your textbook isn't working out so well for you. For example, your diagnosis is only half correct: I think it has to do with the changing sizes of the words but I am not sure That's just a guess. In fact, if we stop being unguided and instead form guesses from the manual for ispunct we find that it accepts an int argument that is expected to be an unsigned char value. As we can see from similar previous questions, assertions are commonly raised for negative char values such as those glyphs from non-English languages. If anything, you need a book such as K&R2e so you establish common idioms that work around these issues rather than wasting months trying to guess why your code throws assertions from within the C standard library, and only getting wrong answers from others who also don't read manuals or textbooks or the like. I strongly recommend less guessing and more reading and doing exercises from your textbook.
70,050,126
70,067,970
Is there any possible way to resize an PNG image in SDL2?
I am using SDL2 and SDL_image.h. My current attempt was trying to fit the .PNG image in a SDL_Rect which only hid my image in the rectangle's area and thus did not work. I was following this tutorial to load the .PNG image. I'm looking to make the image stretch to the same size of the screen which is 640x480. This was my attempt: ... SDL_Rect surfWindRectBC; SDL_Rect surfWindRectCI; SDL_Surface * screenSurf = NULL; SDL_Surface* current = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0, 0, 0); SDL_Surface * menu = IMG_Load(std::string(".\\sprites\\menu\\background.png").c_str()); ... ... int main() { surfWindRectBC.w = SCREEN_WIDTH; surfWindRectBC.h = SCREEN_HEIGHT; surfWindRectCI.w = 32; surfWindRectCI.h = 32; ... ... screenSurf = SDL_GetWindowSurface(window); current = SDL_ConvertSurface(menu, screenSurf->format,0); SDL_FreeSurface(menu); ... ... while (game) { SDL_Event event; Uint8 input = 0; while (SDL_PollEvent(&event)) {...} SDL_BlitSurface(current, &surfWindRectBC, screenSurf, &surfWindRectCI); SDL_UpdateWindowSurface(window); } ...
Looking at documentation maybe you should try using SDL_BlitScaled instead of SDL_BlitSurface
70,050,160
70,050,217
Calling delete on std::stack of pointers
I have a std::stack which has some pointers inside: std::stack<State*> m_states; When I initialize my program, I call new to push an item onto the stack (it must be a pointer because I will use polymorphic types). Is this the correct way of deleting with all the stuff? Here is where I call new (GameState and MenuStatesare classes inherited fromState`): m_states.push(new GameState()); m_states.push(new MenuState()); And this is what I have in the destructor of the whole App class: while (!m_states.empty()) { delete m_states.top(); // (*) m_states.pop(); } Should I only call (*), or do I need to pop() as well?
Should I only call (*) or do I need to pop as well? Well, if you don't call pop() in the while loop, then how will that loop ever end? In other words, how will the condition, !m_states.empty() ever become false? There are other container types (like std::vector) where you could just run through each member, deleting the pointed-to object, and then clear the container, but you can't do that with the std::stack container. That is to say, there is no [] operator for a stack – you can only access the top element.
70,050,271
70,050,303
Access violation reading location 0xFDFDFE01
This is the entire code, i use no header files this code must input a tree and then write out its high, the problem is in the function High() in the line if (tree[headIndex][1] == -1 && tree[headIndex][2] == -1) {, it says : Access violation reading location 0xFDFDFE01. #include<iostream> using namespace std; int** InputTree() { int n, nd, father; int child; char dir; std::cin >> n; int** tree = new int* [n]; for (int i = 0; i < n; i++) { std::cin >> nd; tree[i] = new int[3]; tree[i][0] = nd; tree[i][1] = -1; tree[i][2] = -1; } for (int i = 0; i < n - 1; i++) { std::cin >> father >> child >> dir; if (dir == 'L') tree[father][1] = child; else tree[father][2] = child; } return tree; } int High(int** tree, int headIndex) { if (tree[headIndex][1] == -1 && tree[headIndex][2] == -1) { return 1; } int high1 = High(tree, tree[headIndex][1]); int high2 = High(tree, tree[headIndex][2]); return (high1 > high2 ? high1 : high2); } int main(){ int** t = InputTree(); cout << High(t, 0); system("pause>NULL"); return 0; }
A recursive call to High can be called with headIndex equal to -1. Your recursion only stops when both child nodes are -1, but if one of them is -1 and the other points to another node, you'll make a recursive call and dereference an out-of-bounds index. One way to fix this is to check each node before making the recursive call, for example: int high1 = tree[headIndex][1] == -1 ? 1 : High(tree, tree[headIndex][1]);
70,050,535
70,050,695
Passing array into constructor parameter and creating an array of structs using the value of the array
I am currently writing a class for a polygon that will be drawn onto the screen. My problem however, is that I am unable to figure out how to create an array of structs from an array of arrays (which hold integers, for x and y of each vertex). I am passing this array through the constructor. I assume my error is to do with trying to pass a pointer as an integer, although, after perilous research I can not seem to get my head around how to solve my error. I come from a background of dynamically typed languages (Js and Python mainly) and this is my first large project in a statically typed language. Any help is greatly appreciated. struct Point { int x , y; }; class Polygon { private: Point centre; Polygon(int x, int y, int vertices[]) { centre = {x, y}; struct Point points[sizeof(vertices)/sizeof(vertices[0])] = {vertices}; } //etc.... }; //Example of how it will be called in main.cpp int main{ Polygon polygon(0, 0, {{5,5}, {-5,5}, {5,-5}, {-5,-5}} ); }
How about this? struct Point { int x , y; }; class Polygon { private: Point m_centre; std::vector <Point> m_vec_vertices; public: Polygon(const Point& centre, const std::vector<Point> &vertices) :m_centre(centre), m_vec_vertices(vertices) { } //etc.... }; int main(){ Polygon polygon({0, 0}, {{5,5}, {-5,5}, {5,-5}, {-5,-5}} ); } You defined a point class, in the Polygon constructor why not use it instead of x and y right?
70,050,778
70,051,978
Accessing dimension of boost multi-arrays in C++
When I run the following with warning flags I get a type conversion warning. #include <boost/multi_array.hpp> void function (boost::multi_array<unsigned char, 2> matrix) { int nrows = matrix.shape()[0]; int ncols = matrix.shape()[1]; } See warning message below. Does this mean I am implicitly converting a 'long unsigned int' into a regular 'int'? If so, I think this is what I want (need to perform calculations with nrows, ncols afterwards), and so how would I make the conversion explicit? image.cpp:93:32: warning: conversion to ‘int’ from ‘boost::const_multi_array_ref<float, 2ul, float*>::size_type {aka long unsigned int}’ may alter its value [-Wconversion] int nrows = matrix.shape()[0];
Does this mean I am implicitly converting a 'long unsigned int' into a regular 'int'? Yes, that is what it means. If you don't want the warning then don't make nrows and ncols be of type int. The easiest thing to do is to just let the compiler deduce the type i.e. auto nrows = matrix.shape()[0]; auto ncols = matrix.shape()[1]; or you can make them of type size_t, which is what the standard library uses for the size of containers and won't emit a warning.
70,050,806
70,050,818
Why does std::begin behave differently when called in a nested function
I have some simple code #include<iterator> int main() { int y[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; auto a = std::begin(y); std::cout << *a << std::endl; return 0; } Which prints out 1 as expected. However if I do this : void checkNested(int val [10]) { auto a = std::begin(val); std::cout << *a << std::endl; } int main() { int y[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; checkNested(y); return 0; } I get compilation failures from both clang++ and g++. From clang++ specifically I get: auto a = std::begin(input); ^~~~~~~~~~ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/initializer_list:89:5: note: candidate template ignored: could not match 'initializer_list<type-parameter-0-0>' against 'int *' begin(initializer_list<_Tp> __ils) noexcept ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/range_access.h:48:5: note: candidate template ignored: substitution failure [with _Container = int *]: member reference base type 'int *' is not a structure or union begin(_Container& __cont) -> decltype(__cont.begin()) ^ ~ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/range_access.h:58:5: note: candidate template ignored: substitution failure [with _Container = int *]: member reference base type 'int *const' is not a structure or union begin(const _Container& __cont) -> decltype(__cont.begin()) ^ ~ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/range_access.h:87:5: note: candidate template ignored: could not match '_Tp [_Nm]' against 'int *' begin(_Tp (&__arr)[_Nm]) ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/range_access.h:104:31: note: candidate template ignored: could not match 'valarray<type-parameter-0-0>' against 'int *' template<typename _Tp> _Tp* begin(valarray<_Tp>&); ^ /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/range_access.h:105:37: note: candidate template ignored: could not match 'valarray<type-parameter-0-0>' against 'int *' template<typename _Tp> const _Tp* begin(const valarray<_Tp>&); Just wanna know if there's something really obvious I'm missing here since I expected them to function the same. Thanks
An array can't be passed by value, so your array decays into a pointer when passed to checkNested(), and std::begin() is not defined for a pointer, hence the error. void checkNested(int val [10]) is just syntax sugar for void checkNested(int *val). If you pass the array by reference instead, then the code will work: void checkNested(int (&val) [10])
70,050,839
70,051,065
Can't insert non-const value in unordered_map of references
I'm trying to create 2 std::unordered_map, one holds <A, int> and the second one holds <int&, A&>. I'll explain at the end why I want to do this if you're curious. My problem is that k_i has value of type std::reference_wrapper, k_i.insert doesn't work. But if I make k_i to have value std::reference_wrapper<const A>, the insert works. I just can't figure out why is this and I am curious. <<<<<Edit: The thing is that find returns std::pair<const Ket, T> as stated by Eljay in the comments. Because of this, the second std::unordered_map needs to have the value const. <<<<< Code: Compiler: g++ version 10.1 Compile flags: -Wall -Wextra -std=c++20 #include <unordered_map> #include <iostream> #include <string> #include <functional> class A { public: A(const int x) : x(x) { std::cout << "A::A(const int x) : x(" << x << ")\n"; } A(const A& a) { std::cout << "A::A {" << x << "} (const A& a {" << a.x << "} )\n"; x = a.x; } A(A&& a) { std::cout << "A::A {" << x << "} (A&& a {" << a.x << "} )\n"; x = a.x; } A& operator=(const A& a) { std::cout << "A::operator= {" << x << "} (const A& a)\n"; x = a.x; return *this; } A& operator=(A&& a) { std::cout << "A::operator= {" << x << "} (A&& a)\n"; x = a.x; return *this; } ~A() { std::cout << "A::~A(" << x << ")\n"; } friend std::ostream& operator<<(std::ostream& os, const A& dt); int x; }; std::ostream& operator<<(std::ostream& os, const A& dt) { return os << dt.x; } template <typename K, typename V, typename... args> void print_um(const std::unordered_map<K, V, args...> &umap) { for (const auto &[x, y] : umap) { std::cout << "(" << x << "," << std::ref(y).get() << "); "; } std::cout << "\n"; } template <typename T> struct MyHash { std::size_t operator()(T const& s) const noexcept { return std::hash<int>{}(std::ref(s).get()); } }; template <typename T> struct MyEquals { constexpr bool operator()(const T &lhs, const T &rhs) const { return lhs == rhs; } }; struct MyHash_A { std::size_t operator()(A const& s) const noexcept { return std::hash<int>{}(s.x); } }; struct MyEquals_A { constexpr bool operator()(const A &lhs, const A &rhs) const { return lhs.x == rhs.x; } }; int main() { std::unordered_map<A, int, MyHash_A, MyEquals_A> k_s; std::unordered_map<std::reference_wrapper<int>, std::reference_wrapper<const A>, MyHash<std::reference_wrapper<int>>, MyEquals<std::reference_wrapper<int>>> k_i; { A a(5); std::cout << "1----\n"; k_s[a] = 12; std::cout << "2----\n"; } std::cout << "3----\n"; print_um<>(k_s); std::cout << "4----\n"; A a(5); std::cout << "5----\n"; auto it = k_s.find(a); std::cout << "6----\n"; k_i.emplace((*it).second, (*it).first); // // k_i[(*it).second] = ref_name; std::cout << "7----\n"; print_um<>(k_s); std::cout << "8----\n"; print_um<>(k_i); std::cout << "9----\n"; int x = 12; int &ref = x; auto is_there = k_i.find(ref); if (is_there != k_i.end()) { std::cout << "elem: " << (*is_there).second.get() << "\n"; } else { std::cout << "why? :(\n"; } std::cout << "10---\n"; return 0; } As to why I create this code, I was thinking to be able to access some data by value or by key interchangeably (is there some better data structure? ). Like an username and a token, sometimes I have one, other times I have the other and using references I ensure that I don't waste space. Ofc, if one value has to change, I would invalidate the bucket position in the unordered_map because of the key, but I would treat that problem at a later date. Another motive is to learn some more C++ and test its limits (or mine).
From UnorderedAssociativeContainer requirements: For std::unordered_map and std::unordered_multimap the value type is std::pair<const Key, T>. In your code k_s is unordered_map<A, int>, so the value type is pair<const A, int>. In here: auto it = k_s.find(a); you get a "pointer" to such pair, and type of (*it).first is const A. Your k_i is unordered_map<..., ref<A>> and when you do insert here: k_i.emplace(..., (*it).first); you essentially attempt to initialize ref<A> with const A, which obviously cannot work. When you change k_i type to unordered_map<..., ref<const A>>, then you initialize ref<const A> with const A, which is fine.
70,051,136
70,051,386
Translating text to Morse , not sure how to achieve required output
Need to translate text to Morse for an assignment. The outputted format of the Morse needs to be like this ".../---/... "space" .../---/..." With a space in between words , and a / in between characters. However the / cannot be at the beginning or end of word. Mine outputs like this " .../---/.../ "space" /.../---/.../ " Obviously failing. I am sure there is a simple fix but I seem to be having a meltdown, Please help. // Morse alphabet array String morse [28] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", " " }; // Alphabet array char letters [27] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ' }; // Translates a text char to a morse char String char2Morse (char a) { int b = tolower (a); for (int index = 0; index < 28; index ++) { if ( b == (letters [index])) { return (morse [index]); } } } // Translates a text string into Morse String word2Morse (String wordy) { String returnstring = ""; for (int i = 0; i < wordy.length (); i ++) { returnstring += (char2Morse (wordy[i])); returnstring += ('/'); } return returnstring ; }
The key here is to understand when exactly you would need to add a / after the character. Currently, inside the for loop of word2Morse, you are adding / after translating every character. However, you actually don't want / before or after an word. However, you can't tell the program to not put a slash before or after an word, because it doesn't know what is a word. Instead you need to find a simpler logic. Imagine you are trying to translate the word: hello world You are doing fine translating the first 5 character. However, without any changes to your code, you will add a slash right after the first o, which is not what you want. But why don't you want a slash after o? Because it is the end of a word. And how do you know that? It's because the next character is a space. Now, that's a logic you can explain: You don't want a slash if the next character is a space! So go back to your for loop: for (int i = 0; i < wordy.length (); i ++) { returnstring += (char2Morse (wordy[i])); returnstring += ('/'); } You can add that logic before you add / to your string: for (int i = 0; i < wordy.length (); i ++) { returnstring += (char2Morse (wordy[i])); if (wordy[i+1] != ' ') { returnstring += ('/'); } } Now, you will never add a slash if there's a space after your current character. However, you will have similar problem after the space, and before the letter w. But once again, you can form a similar logic here: You don't want a slash if your current character is a space! This time I will not write the code out, because it should be your homework. But the essence would be to add more boolean test in that if statement. However, there is one more thing to watchout, which is when you are approaching the end of the sentence. Once you have translated the last character d, it would once again try to check if the next character is a space. However, you do not have another character afterwards. And trying to check it will end in errors. So in that if statement, you also want to check you are not at the last character! One other thing to note is that you probably don't want to write out something like: char letters [27] = { 'a', 'b', 'c', 'd', ⋮ ⋮ It's way too repetitive, don't you think? Instead, say if myChar is 'g' , you can get a number by doing myChar - 'a', which would give you 6. So for most of the char2Morse, you can do it like: String char2Morse(char a) { char lower_a = tolower (a); return morse[lower_a - 'a']; } The only thing to catch here is that you can't do it with the space character, which can be tested out with a if-statement: String char2Morse(char a) { if (a == ' ') { return morse[27]; } else { return morse[tolower(a) - 'a']; } }
70,051,204
70,051,584
Visual Studio Debugger: Register a display format for a specific C++ struct/class
How to let the Visual Studio Debugger know that a specific C++/C struct should be displayed in a specific Format? I've for example a C-struct containing 2 pointers that represent the start and end of an array like the following: typedef struct { VEC_VALUE_T* __restrict DataBegin_; VEC_VALUE_T* __restrict DataEnd_; VEC_VALUE_T* __restrict MemEnd_; VEC_ALLOC* __restrict Allocator_; } VEC; How can I display it in the Debugger as if it were a std::vector. The same question from another POV: How does the Debugger know how to display a std::vector? Is std::vector using some debugger specific pragmas or something?
As mentioned by @retired-ninja in comment, the natvis framework can be used: https://learn.microsoft.com/en-us/visualstudio/debugger/create-custom-views-of-native-objects?view=vs-2022 Add natvis file in VS right click on project tab -> Add new item -> Utility -> .natvis Add a type element for that specific struct/class Examples on what the syntax looks like can be found in the link above. In my case the following element definition was sufficient to display it as a std::vector: <?xml version="1.0" encoding="utf-8"?> <AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010"> <Type Name="::VEC"> <DisplayString>{{ size={DataEnd_ - DataBegin_}, capacity={MemEnd_ - DataBegin_} }}</DisplayString> <Expand> <Item Name="[size]" ExcludeView="simple">DataEnd_ - DataBegin_</Item> <Item Name="[capacity]" ExcludeView="simple">MemEnd_ - DataBegin_</Item> <ArrayItems> <Size>DataEnd_ - DataBegin_</Size> <ValuePointer>DataBegin_</ValuePointer> </ArrayItems> </Expand> </Type> </AutoVisualizer>
70,051,330
70,051,471
if deleting top pointer deletes all pointers
I have a doubt. Let’s say that I have implemented a stack in a way similar to a linked list, like this (there are just a push and a print function) #include <iostream> template <class T> struct node{ T data; node<T> *down; }; template <class T> class mystack{ public: node<T> *top = new node<T>; mystack(){top = nullptr; std::cout << "CONSTRUCTION!" << std::endl;} ~mystack(){delete top; std::cout << "DESTRUCTION!" << std::endl;} void push(T elem){ node<T> *new_node = new node<T>; new_node -> data = elem; if (!top){ new_node -> down = top; top = new_node; return; } else{ node<T> *temp = top; new_node -> down = temp; top = new_node; return; } } void print_stack(){ node<T> *temp = top; while(temp){ std::cout << temp -> data << std::endl; temp = temp -> down; } } }; int main(){ mystack<int> st; st.push(20); st.push(200); st.push(2000); st.print_stack(); } my question is: does deleting the top pointer delete all the other pointers or just the first one and the other are still there sitting (hence this code is very bad)?. Plus, would you rather use a smart pointer to do this kind of stuff? Thank you for your time.
Your single delete is insufficient. You need something like: ~mystack() { while(top != nullptr) { node<T> *curr = top; top = top->down; delete curr; } std::cout << "DESTRUCTION!" << std::endl; } That way, you delete every element in your container.
70,051,521
70,051,555
How to pass a 2D arrays of pointers to 3D arrays of pointers (function and class) and return 3d arrays of values in C++?
I am currently working on C++, creating a program of the analysis of matrices. As far as i saw those can be created using an arrays of arrays like this array2D[3][3]={{1,2,3},{4,5,6},{7,8,9}}. Therefore, what i did was to generate a function in a class, such a function must return a 2D array. Then i created another class in order to generate the other array of array of arrays, but this 3D arrays need the data obtained by the previous class, remember the previous class holds the values of the matrix in a variable called int **degreesOfFreedom. Here is where the problem arises this second class needs the values of the double pointer and the problem like this appears. error: cannot convert ‘int***’ to ‘int**’ in assignment As far as i can see the error comes when trying to pass the 2D pointers arrays into the 3D pointers function. By the way i already checked several ways and i saw that one of them is replacing the double pointer ** in the declaration of the variable inside of the function, and replace it by [][]. I already tried that, it didn't solve the problem, also i would not like to do that way because in the future i will have matrices of millions per millions elements. This is my code #include <iostream> #include <string> #include <fstream> class MatrixOfDegreesOfFreedom { public: int X, Y; int M = 0; public: int **matrixOfDegreesOfFreedom(int rows, int cols) { X = rows; Y = cols; int** matrix = new int*[X]; for (int i = 0; i < X; ++i) { matrix[i] = new int[Y]; for (int j = 0; j < Y; ++j) { matrix[i][j] = M; M = M + 1; } } return matrix; } //constructor MatrixOfDegreesOfFreedom() { } //destructor ~MatrixOfDegreesOfFreedom() { } }; class MatrixOfIndexes { public: int X, Y, Z; int M = 0; public: int ***matrixOfIndexes(int rows, int cols, int colsTwo, int conect[][2], int **DoF) { X = rows; Y = cols; Z = colsTwo; int*** matrix = new int**[X]; for (int i = 0; i < X; ++i) { M = 0; matrix[i] = new int*[Y]; for (int j = 0; j < Y; ++j) { matrix[i][j] = new int [Z]; for (int t = 0; t < Z; ++t) { matrix[i][j][t] = DoF[conect[i][j]][t]; } M = M + 1; } } return matrix; } //constructor MatrixOfIndexes() { } //destructor ~MatrixOfIndexes() { } }; int main(int argc, char const *argv[]) { #ifndef OUTPUT freopen("output.txt", "w", stdout); // file to store the output data. #endif int numberOfNodes = 3; // number of nodes int numberOfDegreesOfFreedomPerNode = 2; //Number of Degrees of Freedom per node int **degreesOfFreedom = {}; //number of degree of freedom int numberOfDegreesOfFreedomPerElement = 4; //Number of Degrees of Freedom per element int numberOfElements = 3; int connectivity[numberOfElements][2] = {{0,1},{2,1},{0,2}}; // Conectivity matrix along with the property int **indexes = {}; MatrixOfDegreesOfFreedom tableOfDegreesOfFreedom; degreesOfFreedom = tableOfDegreesOfFreedom.matrixOfDegreesOfFreedom(numberOfNodes, numberOfDegreesOfFreedomPerNode); MatrixOfIndexes tableOfIndexes; indexes = tableOfIndexes.matrixOfIndexes(numberOfElements, numberOfDegreesOfFreedomPerElement, numberOfDegreesOfFreedomPerNode, connectivity, degreesOfFreedom); std::cout<< "finishing" << std::endl; return 0; }
The problem is that the function matrixOfIndexes returns a 3-dimensional pointer (int***) but the array you're assigning that return value to is a two-dimensional one (int**). The types have to match. To fix it just add an extra * to the declaration of indexes: int*** indexes = {};
70,051,666
70,052,326
C++ how to handle file with multiple data types?
I have an input txt file which contains information like this: 4 Eric Nandos 3 15.00 45.00 36.81 64.55 50.50 51.52 36.40 25.15 35.45 24.55 41.55 44.55 36.35 55.50 40.55 Steven Abraham 2 40.45 20.35 40.46 30.35 55.50 18.25 18.00 20.00 30.00 60.65 Richard Mccullen 2 40.45 50.55 20.45 30.30 20.25 30.00 20.00 40.00 60.60 45.45 Stacey Vaughn 3 45.00 25.00 15.00 30.30 25.20 20.20 60.65 55.55 50.50 50.40 30.30 60.55 20.25 20.00 40.00 With getline(file, string) I am able to store this data into a string variable and then output it. The problem is, I need to store the different data types into different variables in order to do certain operations with them (ex: I need to average the decimal values, add the different int values, store some data into a vector, etc). I've tried different loops to parse through the file, but I've been getting an error every time. Any advice on how to separate the different data here so I can store them accordingly? I'm still new to C++ so I don't have much experience. Thank you.
The first line specifies the number of records in the file, where each individual record then consists of: 1 line for a person's name 1 line specifying the number of following lines N number of lines of floating-point numbers You can read such data like this: #include <fstream> #include <sstream> #include <string> #include <limits> ... int numRecords, numLines; std::string name, line; double value; std::ifstream file("filename.txt"); if (!file.is_open()) { // error handling... } if (!(file >> numRecords)) { // error handling ... } file.ignore(std::numeric_limits<streamsize>::max(), '\n'); for (int i = 0; i < numRecords; ++i) { if (!std::getline(file, name)) { // error handling... } // use name as needed... if (!(file >> numLines)) { // error handling... } for (int j = 0; j < numLines; ++j) { if (!std::getline(file, line)) { // error handling... } std::istringstream iss(line); while (iss >> value) { // use value as needed... } if (iss.fail()) { // error handling... } } }
70,052,134
70,052,178
Elegant solution to implementing c++ templates
Inspired by this 2009 question Background: I'm currently working on a small c++ project and decided to try my hand at creating my own templated classes. I immediately ran into a dozen linker errors. As it stands, my understanding is that template specializations aren't generated until they absolutely need to be, and this implies that the implementation of a templated class must be either inlined, or accompanied by an explicit instantiation at the bottom. (Why one implies the other I'm not so sure) Question: Why is that so? Is there something special about the order of compilation that makes it impossible for a compiler to instantiate the template on-demand if it is implemented in a separate .cpp file? In my mind the header and the implementation were simply appended together. Additionally, the question I linked above was initially posted more than ten years ago, and some comments note that the c++-faq quote mentioned is out of date, so I was wondering if newer standards support solutions that enable both separate header/implementation files and implicit instantiation.
Why is it so? As templates compiles through two phases in first phase compiler checks mostly for syntactical errors. If there is no error found in your template is legal to be used, but at this stage compiler do not generate any code for it. And in the second phase compiler will generate the code for all the class members function, of templated functions you used. Because templates are evaluated at compile time. So what happens when compiler compiles it? For example if you defined a template in templated.hpp file and its implementation in implementation.cpp file. Compiler compiles each file separately into an object and then linker link them together. As templates are evaluated at compile time so compiler need its implementation at compile time, which is not available if you are having it in different implementation file. So linkers complains to you that I could not find implementation for type T for your this template. This all happens at compile time. So far until C++20 or even C++23 templates are still needed to be evaluated at compile time albeit C++ has added new concept modules, I am not sure it can be used this way, but you can read about it here.
70,052,228
70,052,281
Why is the move constructor called 2 times?
main.cpp #include <iostream> #include <vector> #include "Person.h" using namespace std; int main() { vector<Person> test{}; test.push_back (Person{ "Chinese", 16 }); test.push_back(Person{}); return 0; } Person.h #pragma once #include <iostream> class Person { public: std::string* ethnicity; int age; Person(std::string ethnicity = "Caucasian", int age = 15); ~Person(); Person(const Person& source); Person (Person&& source) noexcept; }; Person.cpp #include "Person.h" Person::Person(std::string ethnicity, int age) : age(age) { this->ethnicity = new std::string; *this->ethnicity = ethnicity; } Person::Person(const Person& source) : Person(*source.ethnicity, source.age) { std::cout << "Copy constructor deep called!" << std::endl; } Person::Person(Person&& source) noexcept : ethnicity(source.ethnicity), age(source.age) { std::cout << "Move constructor called!" << std::endl; source.ethnicity = nullptr; } Person::~Person() { if (this->ethnicity != nullptr) std::cout << "Destructor called!" << std::endl; else std::cout << "Destructor called for nullptr!" << std::endl; delete ethnicity; } Output From my understanding, only 2 move constructors should be called. But why are 3 move constructors called? The first push_back() should create a temporary object through the constructor, and then the move constructor will be called, then the destructor would be called for the temporary object. The process would be the same for the 2nd push_back(), so in total there would only be 2 move constructors getting called. But why are there 3?
But why are there 3? When std::vector needs more space, it allocates a new array and copies/moves all the existing elements from the old array to the new array. Solution 1 To minimize this, use the std::vector::reserve() member function before pushing elements onto the vector. This pre-allocates the needed space. vector<Person> test; test.reserve(2); test.push_back(Person{"Chinese", 16}); test.push_back(Person{}); Solution 2 Or you can create the vector to be of a particular size, like: vector<Person> test(2); test.at(0) = Person{"Chinese", 16}; test.at(1) = Person{}; Note that in solution 2, we first create a vector of size 2. Now since the std::vector is already of size 2, we do not use push_back because this will mean we add more elements to the vector and the vector size will increase and become 4(if we use push_back 2 times) which is not what we want. What we want now is to set the 0th and 1st index element. Just make sure you handle(or add the assignment operator= if not already) assignment correctly in solution 2.
70,052,270
70,052,398
Why isn't std::hash<const std::string> specialized in std?
Why isn't std::hash<const std::string> specialized in std? It causes compile error like std::unordered_map<const std::string, int> m; m.insert(std::make_pair("Foo", 1)); //error m["Bar"] = 2; // also error Is there any reason for this ?
Why isn't std::hash<const std::string> specialized in std? In fact, std didn't specialize any std::hash<const T>. The reason is probably it's not needed. For any std::hash<T>, the only function it has is an operator(), which takes in const T& as it's argument. So even if std::hash<const Foo> was specialized, it would be exactly the same as std::hash<Foo>. Then go back to the code you were troubling with, it really should've been instead: std::unordered_map<std::string, int> m; Here, despite the key_type is std::string, the actual type of the key is actually const std::string, which can be accessed with decltype(m)::value_type::first_type. Update: When you think of concept of hash, the key should not be changed, so specilaization of std::hash looks more appropriate than std::hash. Don't you agree ? Sure the hash function does not and should not change the key, but in the same time, it probably shouldn't take a copy, so why not go for std::hash<const T&>? One thing to note is that the type being specialized on does not always equal to the argument type. The template argument is more about what type the hash function is related to, not what is passed to the call operator. Similarly, numeric_limits<T> expect a non-cv qualified numeric type as type T. That doesn't mean const int and const double don't have their respective limits. Unless you are expecting different behaviors on hash<T> and hash<const T>, then why should you specialize them twice? And one other thing to notice is that std::hash is really more of a utility class bundled with the unordered_XXX family, and is primarily used as the hash function for the unordered family defaultly, or used to define your custom hash function for your custom types to be supplied to the unordered family.
70,052,298
70,054,262
Speed-up eigen c++ transpose?
I know that this 'eigen speed-up' questions arise regularly but after reading many of them and trying several flags I cannot get a better time with c++ eigen comparing with the traditional way of performing a transpose. Actually using blocking is much more efficient. The following is the code #include <cstdio> #include <ctime> #include <cstdlib> #include <iostream> #include <Eigen/Dense> #define min( a, b ) ( ((a) < (b)) ? (a) : (b) ) int main(){ const int n = 10000; const int csize = 32; float **a, **b; clock_t cputime1, cputime2; int i,j,k,ii,jj,kk; // Allocating memory for array/matrix a = new float * [n]; for (i=0; i<n; i++){ a[i] = new float [n]; } b = new float * [n]; for (i=0; i<n; i++){ b[i] = new float[n]; } // eigen matrices Eigen::MatrixXf M1 = Eigen::MatrixXf::Constant(n, n, 0.0); Eigen::MatrixXf M2 = Eigen::MatrixXf::Constant(n, n, 0.0); // Filling matrices with zeros for(i=0; i<n; ++i) for (j=0; j<n; ++j) a[i][j] = 0; for(i=0; i<n; ++i) for (j=0; j<n; ++j) b[i][j] = 0; // Direct (inefficient) transposition cputime1 = clock(); for (i=0; i<n; ++i) for (j=0; j<n; ++j) a[i][j] = b[j][i]; cputime2 = clock() - cputime1; std::printf("Time for transposition: %f\n", ((double)cputime2)/CLOCKS_PER_SEC); // Transposition using cache-blocking cputime1 = clock(); for (ii=0; ii<n; ii+=csize) for (jj=0; jj<n; jj+=csize) for (i=ii; i<min(n,ii+csize-1); ++i) for (j=jj; j<min(n,jj+csize-1); ++j) a[i][j] = b[j][i]; cputime2 = clock() - cputime1; std::printf("Time for transposition: %f\n", ((double)cputime2)/CLOCKS_PER_SEC); // eigen cputime1 = clock(); M1.noalias() = M2.transpose(); cputime2 = clock() - cputime1; std::printf("Time for transposition with eigen: %f\n", ((double)cputime2)/CLOCKS_PER_SEC); // use data std::cout << a[n/2][n/2] << std::endl; std::cout << b[n/2][n/2] << std::endl; std::cout << M1(n/2,n/2) << std::endl; return 0; } And the compiling command I am using is g++ -fno-math-errno -ffast-math -march=native -fopenmp -O2 -msse2 -DNDEBUG blocking_and_eigen.cpp with results Time for transposition: 1.926674 Time for transposition: 0.280653 Time for transposition with eigen: 2.018217 I am using eigen 3.4.0, and g++ 11.2.0. Do you have any suggestion to improve eigen performance? Thanks in advance
As suggested by INS in the comment is the actual copying of the matrix causing the performance drop, I slightly modify your example to use some numbers instead of all zeros (to avoid any type of optimisation): for(i=0; i<n; ++i) { for (j=0; j<n; ++j) { a[i][j] = i+j; M1(i,j) = i+j; } } for(i=0; i<n; ++i) { for (j=0; j<n; ++j) { b[i][j] = i+j; M1(i,j) = i+j; } } Also, I modify the final printing statement with a full check over the result (when not in place the check will be performed against M2): for (i=0; i<n; ++i) for (j=0; j<n; ++j) if (a[i][j] != M1(i,j)) std::cout << "Diff here! " << std::endl; Then I tried several tests: Preallocation and assignment Eigen::MatrixXf M2 = Eigen::MatrixXf::Constant(n, n, 0.0); ... some code here ... M2 = M1.transpose(); Copy constructor Eigen::MatrixXf M2(M1.transpose()); in place M1.transposeInPlace(); copy construct using auto and c++17 auto M2{ M1.transpose() }; This is the most puzzling, the performance are outstanding, I think there are two part in the story, if I print the typeid name of M2 for case 2 and 4 they are different, and the name is mangled but it give us a clue: N5Eigen6MatrixIfLin1ELin1ELi0ELin1ELin1EEE N5Eigen9TransposeINS_6MatrixIfLin1ELin1ELi0ELin1ELin1EEEEE auto keyword resolve to a different type specific for transpose matrix. The second part of the story is the fact that M1 is not modify afterwards, so either the compiler moves it or, most likely the EigenTransposeMatrix (https://eigen.tuxfamily.org/dox/classEigen_1_1Transpose.html) is only keeping a reference of the original matrix and it doesn't copy it. Results Test Direct (s) Cache block (s) eigen (s) 1 2.633 0.312 1.861 2 2.599 0.262 1.968 3 2.602 0.262 0.216 4 2.552 0.280 0.000002
70,052,348
70,052,414
Program stuck in Infinite loop
My program is going in infinite loop and does not print required output please help anyone
On the 2nd and subsequent iterations of the outer while loop, space will be initialized with a non-zero value, and then the while(space) loop will keep incrementing space for a long time until it overflows to a negative value, and then keep looping for a long time further until space eventually increments to 0, finally breaking the loop. When an int is evaluated as a boolean, only 0 evaluates as false, all other values evaluate as true. And a 32bit int can hold 4294967296 unique values (-2147483648..2147483647), giving the illusion that your loop is infinite.
70,052,690
70,053,145
C++ How to handle user input given in contests/problems format
Recently I have been starting to participate in c++ contests but I cannot find the best way to handle user input when given in this format. E.g. 4 and 3 are the dimensions of the next block of input 4 3 1 2 4 5 1 6 7 4 1 5 0 0 The problem I've been having is that sometimes the automatic testing machine successfully can test its inputs and sometimes no, so far the method I've been using is the next std::vector<std::vector<char>> vec; void get_lines(std::string in) { std::vector<char> line(in.begin(), in.end()); vec.push_back(line); } std::cin >> height >> width;//this is in main() std::cin.ignore(); for (int i = 0; i < height; i++) { std::getline(std::cin, input); get_lines(input); input = ""; } But I'm sure it's not the most efficient nor the more stable way to handle this type of input. How can I handle user input in the above-mentioned format so that the testing machine can easily input its values?
First of all, I am sorry for you that you made the decision to participate in such contests. It will help you to learn on how to solve algorithms, but they usually use an extremely bad programming style. Anyway. Back to your question. As always. It depends. If you have data that are just separated by white space, you can use nearly always formatted input functions with the extractor operator ´>>´. This operator will ignore (skip) all white space in standard mode, including the "new line" at the end of a line. So, no need to read line by line. The good point ofthis "contest pages" is that input is always be considered correct. So, you do not need to do input-error checking or data plausibilisation. The will always use some test environment, where they "push" the data in your code via input redirection. In real life, user input is always very error prone and must be checked carefully. And you see that, although not necessary, they give the dimensions of the matrix, to ease up data input (this would normally not be necessary, because we can find out by ourselves). So, first read the dimensions. With that, construct your ´std::vector´ Then use 2 nested range based for loops to read the values One of many possible examples could look like this: #include <iostream> #include <vector> int main() { // Define variables that will hold the dimension of the matrix size_t numberOfRows{}, numberOfColumns{}; // Get user input, the dimension of the matrix std::cin >> numberOfRows >> numberOfColumns; // Define our container, including its size std::vector<std::vector<int>> matrix(numberOfRows, std::vector<int>(numberOfColumns, 0)); // Read values from user input for (std::vector<int>& row : matrix) for (int& i : row) std::cin >> i; // Show output for (const std::vector<int>& row : matrix) { for (const int& i : row) std::cout << i << ' '; std::cout << '\n'; } } Also the use of std::istream_iterators in conjunction with range constructors can be used here. But, as said. It depends. If they have Comma Separated Values, or white space within values, like strings, then you need to use other mechanisms.
70,053,247
70,053,357
How do I setup the width?
We are given an assignment wherein we are supposed to output a given txt file and solve for the BMI. However, I am having problems with how to output the data as it is not following my desired alignment. Any help would be appreciated! I apologize if my question is very simple as I am not that good at programming. Here is the txt file: Here is my code: #include <iostream> #include <iomanip> #include <fstream> #include <stdio.h> #include <string> using namespace std; int main() { string line = ""; ifstream inFile; inFile.open("homework.txt"); cout << setw (3) << "NO " << setw (10) << "FIRSTN " << setw (10) << "LASTN " << setw (7) << "WEIGHT " << setw (7) << "HEIGHT " << setw (4) << "BMI " << endl ; if (inFile.is_open()) { while (getline(inFile, line, '#')) { cout << line << left << setw(10); } } inFile.close(); return 0; } Here is the result: *I have not yet worked on with how the BMI would be computed and displayed.
One possible way would be : #include <iostream> #include <iomanip> #include <fstream> #include <stdio.h> #include <string> using namespace std; int main() { string no, firstin, lastin, weight, height; ifstream inFile; inFile.open("homework.txt"); std::cout << std::setw(13) << std::setfill(' ') << "NO" << std::setw(13) << std::setfill(' ') << "FIRSTIN" << std::setw(13) << std::setfill(' ') <<"LASTIN" << std::setw(13) << std::setfill(' ') << "WEIGHT" << std::setw(13) << std::setfill(' ') << "HEIGHT" << std::setw(13) << std::setfill(' ') <<"BMI" <<std::endl; if (inFile.is_open()) { //correct this for reading upto '\n' while (getline(inFile, no, '#'), getline(inFile, firstin, '#'), getline(inFile, lastin, '#'), getline(inFile, weight, '#'), getline(inFile, height, '\n') //read upto '\n' instead of '#' ) { std::cout << std::setw(13) << std::setfill(' ') << no << std::setw(13) << std::setfill(' ') << firstin << std::setw(13) << std::setfill(' ') <<lastin << std::setw(13) << std::setfill(' ') << weight << std::setw(13) << std::setfill(' ') << height << std::setw(13) << std::setfill(' ') << "MBI" //write whatever bmi value here <<std::endl; } } inFile.close(); return 0; } The output of the above program is: NO FIRSTIN LASTIN WEIGHT HEIGHT BMI 1 Hannah Cruz 130 5'4 BMI 2 Franches Ramire 137 5'6 BMI which can be seen here. Also note since your question specifically asked for alignment and not for how to calculate bmi, i have not calculated it in my above program. You can calculate it and then use that value in the last column instead of the hard coded string literal bmi.
70,053,253
70,054,954
How to change type of elements in C++ boost multi array?
I receive a matrix with elements of type unsigned char from another function and I am trying to find its max value. boost::multi_array<unsigned char, 2> matrix; All elements are integers and so I was hoping to recast matrix as type <int, 2> then perform std::max_element() operation, but unsure how to recast type of a boost multi array.
You don't need that to use max_element. char is an integral type just like int: Live On Compiler Explorer #include <boost/multi_array.hpp> #include <fmt/ranges.h> #include <algorithm> int main() { using boost::extents; boost::multi_array<unsigned char, 2> matrix(extents[10][5]); std::iota( // matrix.data(), // matrix.data() + matrix.num_elements(), '\x30'); fmt::print("matrix: {}\n", matrix); auto [a, b] = std::minmax_element(matrix.data(), matrix.data() + matrix.num_elements()); // as integers fmt::print("min: {}, max {}\n", *a, *b); // as characters fmt::print("min: '{:c}', max '{:c}'\n", *a, *b); } Program stdout matrix: {{48, 49, 50, 51, 52}, {53, 54, 55, 56, 57}, {58, 59, 60, 61, 62}, {63, 64, 65, 66, 67}, {68, 69, 70, 71, 72}, {73, 74, 75, 76, 77}, {78, 79, 80, 81, 82}, {83, 84, 85, 86, 87}, {88, 89, 90, 91, 92}, {93, 94, 95, 96, 97}} min: 48, max 97 min: '0', max 'a' Reinterpreting View If you must (for other reasons thatn using max_element) you can use a multi_array_ref: // reinterpreting view: boost::multi_array_ref<const char, 2> view( reinterpret_cast<const char*>(matrix.data()), std::vector(matrix.shape(), matrix.shape() + 2)); fmt::print("view: {}\n", view); Which prints Live On Compiler Explorer view: {{'0', '1', '2', '3', '4'}, {'5', '6', '7', '8', '9'}, {':', ';', '<', '=', '>'}, {'?', '@', 'A', 'B', 'C'}, {'D', 'E', 'F', 'G', 'H'}, {'I', 'J', 'K', 'L', 'M'}, {'N', 'O', 'P', 'Q', 'R'}, {'S', 'T', 'U', 'V', 'W'}, {'X', 'Y', 'Z', '[', '\'}, {']', '^', '_', '`', 'a'}} You can also reshape it: view.reshape(std::vector{25, 2}); fmt::print("reshaped: {}\n", view); Printing reshaped: {{'0', '1'}, {'2', '3'}, {'4', '5'}, {'6', '7'}, {'8', '9'}, {':', ';'}, {'<', '='}, {'>', '?'}, {'@', 'A'}, {'B', 'C'}, {'D', 'E'}, {'F', 'G'}, {'H', 'I'}, {'J', 'K'}, {'L', 'M'}, {'N', 'O'}, {'P', 'Q'}, {'R', 'S'}, {'T', 'U'}, {'V', 'W'}, {'X', 'Y'}, {'Z', '['}, {'\', ']'}, {'^', '_'}, {'`', 'a'}}
70,053,390
70,056,867
How to send .mp4 file over TCP in C/C++?
I am trying to send files over TCP client/server in C++ app. The scenario is pretty simple; Client side send files and server side receive files. I can send text based(such as .cpp or .txt) files successfully, but when I try to send files such as .mp4 or .zip, the files received on the server are corrupted. client.cpp FILE *fptr = fopen(m_fileName.c_str(), "rb"); off_t offset = 0; int bytes = 1; if(fptr){ while (bytes > 0){ bytes = sendfile(m_sock, fptr->_fileno, &offset, BUFFER_SIZE); std::cout<< "sended bytes : "<< offset << '\n'; } } fclose(fptr); std::cout<< "File transfer completed!\n"; Server.cpp //some stuff... for (;;) { if ((m_result = recv(epes[i].data.fd, buf, BUFFER_SIZE, 0)) == -1) { if (errno == EAGAIN) break; exit_sys("recv"); } if (m_result > 0) { buf[m_result] = '\0'; std::ofstream outfile; if(!outfile.is_open()) outfile.open(m_filename.c_str(), std::ios_base::app | std::ios_base::binary); outfile << std::unitbuf << buf; m_filesize -= m_result; std::cout << "count : " << m_result << '\n'; std::cout << "remain data : " << m_filesize << '\n'; if(!m_filesize){ outfile.close(); m_fileTransferReady = 0; std::cout<<"File transfer stop\n"; if (send(epes[i].data.fd, "transferok", 10, 0) == -1) exit_sys("send"); } } //some stuff for else } I used binary mode when sending and receiving files, but I guess that's not enough. Is there a special sending method for formatted files?
I found the solution by going the way G.M. mentioned in the comment. Adding a null character to the end of a file opened in binary mode causes problems for non-text-based files. Another issue is with the use of the << operator. Instead ofstream's write member function needs to be used. As a result; server.cpp //... //... if (m_result > 0) { //buf[m_result] = '\0'; //Deleted! std::ofstream outfile; if(!outfile.is_open()) outfile.open(m_filename.c_str(), std::ios_base::app | std::ios_base::binary); outfile << std::unitbuf; //Modified outfile.write(buf, m_result); //Added m_filesize -= m_result; //... //...
70,053,971
70,054,410
Cost of copy vs move std::shared_ptr
Why would I std::move an std::shared_ptr? Answers to this question point out that moving a std::shared_ptr is all about speed, but nobody explains why it is faster in detail. How expensive is it really in comparison? Is it worth optimzing when one uses it a lot?
I wrote a benchmark. On my Macbook Air it is three times faster (g++ as well as clang++ -std=c++17 -O3 -DNDEBUG). Let me know if you see problems with the benchmark. #include <chrono> #include <iostream> #include <vector> #include <memory> using namespace std; using namespace std::chrono; int COUNT = 50'000'000; struct TimeIt { system_clock::time_point start; TimeIt() { start = system_clock::now(); } ~TimeIt() { auto runtime = duration_cast<milliseconds>(system_clock::now()-start).count(); cout << runtime << " ms" << endl; } }; void benchmark_copy(const vector<shared_ptr<int>> &vec_src) { cout << "benchmark_copy" << endl; vector<shared_ptr<int>> vec_dst; vec_dst.reserve(COUNT); TimeIt ti; for(auto &sp : vec_src) vec_dst.emplace_back(sp); } void benchmark_move(vector<shared_ptr<int>> &&vec_src) { cout << "benchmark_move" << endl; vector<shared_ptr<int>> vec_dst; vec_dst.reserve(COUNT); TimeIt ti; for(auto &sp : vec_src) vec_dst.emplace_back(move(sp)); } int main (int arg, char **argv){ vector<shared_ptr<int>> vec; for (int i = 0; i < COUNT; ++i) vec.emplace_back(new int); benchmark_copy(vec); benchmark_move(move(vec)); }
70,054,164
70,054,336
ARM GCC removing required code during optimization
I have the following code that does a really basic conversion from 16bpp image to a 1bpp image, the code functions as expected until I enable compiler optimizations, at which point I just get a black image. #define RSCALE 5014709 #define GSCALE 9848225 #define BSCALE 1912602 uint16_t _convertBufferTo1bit(uint8_t* buffer, uint16_t size) { uint8_t* dst_ptr = buffer; uint8_t* end_ptr = buffer + size; uint16_t pos = 0; uint8_t r, g, b, i; uint32_t lum; while(buffer < end_ptr) { for(i = 8; i > 0; i--) { r = (*buffer & 0xF8); g = ((*buffer & 0x07) << 5); buffer += 1; g |= (*buffer & 0x03); b = ((*buffer & 0x1F) << 3); buffer += 1; lum = ((RSCALE * r) + (GSCALE * g) + (BSCALE * b)); if(lum > 0x7FFFFFFF) { //White dst_ptr[pos] |= (1 << (i-1)); } else { //black dst_ptr[pos] &= ~(1 << (i-1)); } } pos++; } return pos; } When looking at the decompiled assembly I can see that the if(lum > 0x7FFFFFFF) statement and all associated calculations have been removed by the compiler. Can someone help me understand why? -O0 -std=c++17 -Wall -Wextra https://godbolt.org/z/GhPezzh33 -O1 -std=c++17 -Wall -Wextra https://godbolt.org/z/bn1M4319h
In this code: lum = ((RSCALE * r) + (GSCALE * g) + (BSCALE * b)); if(lum > 0x7FFFFFFF) RSCALE, GSCALE, and BSCALE are 5014709, 9848225, and 1912602, respectively. Assuming int is 32 bits in the C implementation being used, these are all int constants. r, g, and b are all of type uint8_t, so they are promoted to int in the multiplications. Then ((RSCALE * r) + (GSCALE * g) + (BSCALE * b)) is a calculation entirely with int operands producing an int result. So the compiler can see that lum is assigned the value of an int result, and it is entitled to assume the result is in the range INT_MIN to INT_MAX. Further, it can see all operands are nonnegative, and therefore negative results are not possible, reducing the possible range to 0 to INT_MAX. This excludes the possibility that assigning a negative value to a uint32_t will cause wrapping to a high value. So the compiler may assume lum > 0x7FFFFFFF is never true. The calculation may overflow int, and then the behavior is undefined, and the compiler is still allowed to use the assumption. To correct this, change at least one operand of each multiplication to unsigned.
70,054,197
70,054,357
How to iterate map<int, vector <int>>?
I have map<int, vector > like this: #include <iostream> #include <map> #include <vector> using namespace std; int main() { map<int, vector <int>> someMap; someMap[5] = {5, 2, 3, 7}; someMap[151] = {5, 9, 20}; return 0; } I need to find the last vector element in each map value. Output must be like this: 7 20 Thanks :)
You can use the std::vector::back member function as shown below: #include <iostream> #include <map> #include <vector> #include <cassert> using namespace std; int main() { map<int, vector <int>> someMap; someMap[5] = {5, 2, 3, 7}; someMap[151] = {5, 9, 20}; //iterate through each element of the map for(const std::pair<int, std::vector<int>> &myPair: someMap) { //make sure the vector is not empty assert(!myPair.second.empty()); //print the last element in the vector std::cout << myPair.second.back() <<std::endl; } return 0; } The output of the above program is: 7 20 which can be seen here.
70,054,580
70,063,693
stringstream does not allocate integers to integer vector
I have a string of different integers separated by a comma. For example "45,67,2,3,8,9,123,5,6,3,9,4,7,2,4,4,5,69,9,99". I want to read this line as a stringstream and put integers to the vector of integers. On the console, it displays "no response on stdout". The code looks as follows: #include <sstream> #include <vector> #include <iostream> using namespace std; vector<int> parseInts(string str) { stringstream myString; vector<int> of_integers; char ch; int a; for(int k = 0; k<str.size(); k++) { myString >> a >> ch; of_integers[k] = a; } return of_integers; } int main() { string str; cin >> str; vector<int> integers = parseInts(str); //function parseInts for(int i = 0; i < integers.size(); i++) { cout << integers[i] << "\n"; } return 0; }
The working code: #include <sstream> #include <vector> #include <iostream> using namespace std; vector<int> parseInts(string str) { stringstream myString(str); int size = str.size(); vector<int> of_integers; char ch = ','; int a=0; while(myString.eof()!=1) { myString >> a >> ch; of_integers.push_back(a); } return of_integers; } int main() { string str; cin >> str; vector<int> integers; integers = parseInts(str); for (int i = 0; i < integers.size(); i++) { cout << integers[i] << "\n"; } return 0; } Thanks for @jpmarinier, for referencing an useful stringstream function .eof() that detects when the stringstream ended. The code worked well. Input: 45,67,2,3,8,9,123,5,6,3,9,4,7,2,4,4,5,69,9,99 Output: 45 67 2 3 8 9 123 5 6 3 9 4 7 2 4 4 5 69 9 99
70,054,587
70,054,986
Why C++ static data members are needed to define but non-static data members do not?
I am trying to understand the difference between the declaration & definition of static and non-static data members. Apology, if I am fundamentally miss understood concepts. Your explanations are highly appreciated. Code Trying to understand class A { public: int ns; // declare non-static data member. static int s; // declare static data member. void foo(); }; int A::s; // define non-static data member. // int A::ns; //This gives an error if defined. void A::foo() { ns = 10; s = 5; // if s is not defined this gives an error 'undefined reference' }
When you declare something, you're telling the compiler that the name being declared exists and what kind of name it is (type, variable, function, etc.) The definition could be with the declaration (as with your class A) or be elsewhere—the compiler and linker will have to connect the two later. The key point of a variable or function definition is that it tells the compiler and linker where this variable/function will live. If you have a variable, there needs to be a place in memory for it. If you have a function, there needs to be a place in the binary containing the function's instructions. For non-static data members, the declaration is also the definition. That is, you're giving them a place to live¹. This place is within each instance of the class. Every time you make a new A object, it comes with an ns as part of it. Static data members, on the other hand, have no associated object. Without a definition, you've got a situation where you have N instances of A all sharing the same s, but nowhere to put s. Therefore, C++ makes you choose one translation unit for it via a definition, most often the source file that acommpanies that header. You could argue that the compiler should just pick one instance for it, but this won't work for various reasons, one being that you can use static data members before ever creating an instance, after the last instance is gone, or without having instances at all. Now you might wonder why the compiler and linker still can't just figure it out on their own, and... that's actually pretty much what happens if you slap an inline on the variable or function. You can end up with multiple definitions, but only one will be chosen. 1: Giving them a place to live is a little beside the point here. All the compiler needs to know when it creates an object of that class is how much space to give it and which parts of that space are which data members. You could think of it as the compiler doing the definition part for you since there's only one place that data member could possibly live.
70,054,624
70,065,643
Unknown protocol: protocolId = 92, protocolName = CbdProto, servicePrimitive = REQUEST
I try to implement a Network Layer Protocol, using the INET SensorNode module. I properly extend the NED simple module as follow : simple CbdProto extends NetworkProtocolBase like INetworkProtocol { @class(inet::CbdProto); } This protocol is added to the list of the INET Procotol class (Protocol.cc) by extending that class : In ProtocolNew.h static const ProtocolNew CbdProto; In ProtocolNew.cc const ProtocolNew ProtocolNew::CbdProto("CbdProto","Network Protocol",ProtocolNew::NetworkLayer); The C++ class is settled up accordingly. I register the protocol in initialize() method : void inet::CbdProto::initialize(int stage) { if (stage == INITSTAGE_NETWORK_LAYER) { registerProtocol(ProtocolNew::CbdProto, gate("transportOut"), gate("transportIn")); } } The .ini file is as follow : **.hasIpv4 = false **.hasIpv6 = false **.hasGn = true **.generic.typename = "SimpleNetworkLayer" **.generic.np.typename = "CbdProto" But I keep having this error that I don't know to fix it. <!> handlePacket(): Unknown protocol: protocolId = 92, protocolName = CbdProto, servicePrimitive = REQUEST, pathStartGate = WsnCbd.s[0].udp.ipOut, pathEndGate = WsnCbd.s[0].tn.in[0] -- in module (inet::MessageDispatcher) WsnCbd.s[0].tn (id=18), at t=0s, event #6 Please, I will appreciate your input. Thanks
You don't have to create a new class. You just have to add your new protocol to the Protocol.cc and .h file, to the existing Protocol. (Don't forget to create an instance in the .cc file. Your new protocol provides a service to the upper layer so you have to use registerService() in your protocol's code.
70,054,650
70,054,694
How const char* strings are compared?
Firstly, consider this example: #include <iostream> using namespace std; int main() { cout << ("123" == "123"); } What do I expect: since "123" is a const char*, I expect ADDRESSES (like one of these answers said) of these strings to be compared. ... because != and == will only compare the base addresses of those strings. Not the contents of the strings themselves. But still the output is 1. Okay, we actually don't know how to compare addresses of two prvalue objects (or at least I don't understand how it would be done). So let's declare these strings as variables and see what will happen: #include <iostream> using namespace std; int main() { const char* a = "1230"; const char* b = "1230"; cout << (a == b); } Still the output is 1. So const char* strings does not decay? Or compiler managed to do some optimizations and allocate memory only for one string? Ok, let's try to avoid them: #include <iostream> using namespace std; int main() { const char* a = "1230"; const char* b = "1231"; b = "1230"; cout << (a == b); } Still the result is the same. Which made me think that const char* really does not decays. But that didn't made my life simpler. How then const char*s are compared? Why here the output is 1: #include <iostream> using namespace std; int main() { const char* a = "1230"; const char* b = "1231"; cout << (a > b); } a is less than b, in terms of lexographical comparison, but here a is bigger. How then comparison of const char*s is implemented?
Yes, the linked answer is correct. operator== for pointers just compares the addresses, never their content. Furthermore, the compiler is free, but not required, to de-duplicate string literals, so all occurrences of a string literal are the same object, with the same address. That is what you observe and re-assignment b = "1230"; won't stop that. [lex.string.14] Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above. Whether all string-literals are distinct (that is, are stored in nonoverlapping objects) and whether successive evaluations of a string-literal yield the same or a different object is unspecified. What should const char* decay to? Arrays decay, pointers don't. #include <iostream> using namespace std; int main() { const char* a = "1230"; const char* b = "1231"; cout << (a > b); } returns 1 just because a happens to point to a higher address than b, there is no lexiographical comparison done. Just use std::string or std::string_view if you require that.
70,054,880
70,055,025
What is the casting order of operations in arithmetics in c++?
Why does result = static_cast<double>(1 / (i+1)) return int in C++ and why does result = 1 / (i+static_cast<double>(1)) return double? Specifically why is casting after the +-operation sufficient to produce a double. Why is it not required before the + or in the numerator as well? Is static_cast the preferred way of casting? Code: double harmonic(int n) { double result = 0; for (int i = 0; i < n; i++) { result += 1 / static_cast<double>(i+1); } return result; }
There's no such thing as "casting order" because the type of an expression depends on its operands. Put it simply, if a binary arithmetic operator accepts two operands of different types then the smaller type will be implicitly converted to the wider type In result = static_cast<double>(1 / (i+1)) it's parsed like this i + 1 is an int expression since both i and 1 are of type int 1 / (i + 1) returns int for the same reason Then the result of 1 / (i + 1) is statically cast to double OTOH in result = 1 / (i+static_cast<double>(1)) it's like this 1 is cast to double i + static_cast<double>(1) returns double because i is cast to double due to the other operand 1 / (i+static_cast<double>(1)) is a double expression for the same reason But no one cast like that. It's better to do 1 / (i + 1.0) instead The complete rule is like this If either operand has scoped enumeration type, no conversion is performed: the other operand and the return type must have the same type Otherwise, if either operand is long double, the other operand is converted to long double Otherwise, if either operand is double, the other operand is converted to double Otherwise, if either operand is float, the other operand is converted to float Otherwise, the operand has integer type (because bool, char, char8_t, char16_t, char32_t, wchar_t, and unscoped enumeration were promoted at this point) and integral conversions are applied to produce the common type, as follows: If both operands are signed or both are unsigned, the operand with lesser conversion rank is converted to the operand with the greater integer conversion rank Otherwise, if the unsigned operand's conversion rank is greater or equal to the conversion rank of the signed operand, the signed operand is converted to the unsigned operand's type. Otherwise, if the signed operand's type can represent all values of the unsigned operand, the unsigned operand is converted to the signed operand's type Otherwise, both operands are converted to the unsigned counterpart of the signed operand's type. The conversion rank above increases in order bool, signed char, short, int, long, long long. The rank of any unsigned type is equal to the rank of the corresponding signed type. The rank of char is equal to the rank of signed char and unsigned char. The ranks of char8_t, char16_t, char32_t, and wchar_t are equal to the ranks of their underlying types. Arithmetic operators
70,055,219
70,056,483
Why does passing a parameter pack to a function with one template parameter call it multiple times?
Take this code: template<typename T> int foo() { std::cout << "foo called" << std::endl; return 10; }; template<typename... Ts> std::vector<int> bar(Ts... ts) { std::vector<int> vec{foo<Ts>()...}; return vec; }; int main() { std::vector<int> vec = bar(1,2,3,4); } The code above outputs: foo called foo called foo called foo called How is this possible? I thought I had understood template parameter packs, but how does the line std::vector<int> vec{foo<Ts>()...}; cause foo to be called multiple times? Is foo returning a parameter pack, since we use the ... operator on the function call? What's going on this code?
foo<T>()... is expanded to foo<T1>(), foo<T2>(), foo<T2>(), .... In your case, since your vector has four components, your function will be called four times with the expansions.
70,055,308
70,055,455
"Pointer to incomplete class type is not allowed"
For some reason I cannot use the "getNotify()" function attached to the "Broker" object. I added a comment to the line that is not working(in "Publisher" class). As an error I get "Error; pointer to incomplete class type is not allowed" Please help the "Broker" class is implemented with Singleton-Pattern Broker.h class: #ifndef DEF_Broker #define DEF_Broker #include <iostream> #include "classes.h" using namespace std; class Broker : Publisher { static Broker *instance; Broker(); public: static Broker* getInstance() { if(!instance) { instance = new Broker(); } return instance; } void getNotify() { for(auto sub : SubscriberList) { if(t.msg == "Hello World") { SubCount++; cout << SubCount << " - "; sub->update(t.msg); } else if(t.msg == "Ping") { cout << "Ping" << endl; sub->update("Pong"); } } } }; Broker *Broker::instance = 0; // Null, because instance will be initialized on demand. Broker::Broker(){}; // Private constructor so that no objects can be created. #endif classes.h : #ifndef DEF_classes #define DEF_classes #include <iostream> #include <list> using namespace std; class Broker; class Subscriber { public: void update(string msg) { cout << msg << endl; } }; class Topic { public: string msg; Topic(){}; Topic(string msg) { this->msg = msg; } }; class Publisher { protected: list<Subscriber*> SubscriberList; static int SubCount; public: Topic t; Broker *broker;// = broker->getInstance(); Publisher(){} Publisher(Topic t) { this->t = t; }; void AddSub(Subscriber *sub) { SubscriberList.push_back(sub); } void notify(string msg) { broker->getNotify(); // this not working } }; int Publisher::SubCount = 0; // Initialize static member SubCount #endif
Normally you would need to include broker.h in classes.h, however, this would create a circular dependency. Therefore, implement the functions of Publisher in a .cpp file and include broker.h in that file. The forward declaration in classes.h (class broker;) needs to remain.
70,055,336
70,055,388
Is there a way to call the destructor of a replaced element when using std::replace?
I have a vector of objects where I want to replace one element by another. Using std::replace seemed appropriate, so I gave it a try. I was concerned about the whereabouts of the replaced element though, so I did some tests : #include <iostream> #include <vector> #include <algorithm> class A { public: A(const int ii) : i(ii) { std::cout << "Constructor " << i << std::endl;} ~A(){std::cout << "Destructor " << i << std::endl;} auto operator ==(const A& a){ return i == a.i;} int i; }; int main() { std::vector<A> v; v.reserve(4); v.emplace_back(10); v.emplace_back(20); v.emplace_back(40); v.emplace_back(30); for(const auto& elt : v){ std::cout << elt.i << ' '; } std::cout << std::endl; std::replace(v.begin(), v.end(), v[2], A(25)); for(const auto& elt : v){ std::cout << elt.i << ' '; } std::cout << "End of program" << std::endl; } Third element of the vector is replaced, but as you can see the replaced object destructor isn't called : Constructor 10 Constructor 20 Constructor 40 Constructor 30 10 20 40 30 Constructor 25 Destructor 25 10 20 25 30 End of program Destructor 10 Destructor 20 Destructor 25 Destructor 30 As the behaviour is the same on every compiler, I suppose it's intended, but is there a way to have the destructor called in that case ? Testing example : https://godbolt.org/z/YTaKcrTEn Thanks !
From cppreference on std::replace: Because the algorithm takes old_value and new_value by reference, it can have unexpected behavior if either is a reference to an element of the range [first, last). Therefore, this is wrong: std::replace(v.begin(), v.end(), v[2], A(25)); Indeed, we can't choose old_value to be a reference to v[2] as done here. Consider instead: A to_replace{v[2]}; // copy std::replace(v.begin(), v.end(), to_replace, A(25)); You can also force the copy without using an additional variable (as Staz suggests): std::replace(v.begin(), v.end(), A{v[2]}, A(25));
70,055,550
70,055,765
Resolution of class template with different default template argument and partial specialization argument
I have two class (struct) templates A and B, which are identical except that the second parameter's default argument (in their primary templates) and the template-specializing second argument (in their partial specializations) are the same in A (both void), while different in B (void and int respectively). #include <bits/stdc++.h> /* primary class template A */ template <int N, class = void> struct A : std::false_type {}; /* partial specialization of A */ template <int N> struct A<N, std::enable_if_t<(N != 0), void>> : std::true_type {}; /* primary class template B */ template <int N, class = void> struct B : std::false_type {}; /* partial specialization of B */ template <int N> struct B<N, std::enable_if_t<(N != 0), int>> : std::true_type {}; int main() { std::cout << A<0>::value << std::endl; // 0 (i.e. A<0> extends std::false_type) std::cout << A<1>::value << std::endl; // 1 (i.e. A<1> extends std::true_type) std::cout << B<0>::value << std::endl; // 0 (i.e. B<0> extends std::false_type) std::cout << B<1>::value << std::endl; // 0 (i.e. B<1> extends std::false_type) return 0; } As is understood from the output, B<1> resolves to the primary template whereas A<1> resolves to the partial specialization, which I guess happens due to the aforementioned difference. This is rather counterintuitive as I expected the exact opposite to happen. But why does it happen? How does the compiler decide which version to resolve, particularly in this case? Edit: As @Enlinco correctly identifies in his answer, my confusion was due to expecting that, when instantiating B<1>, the compiler would resolve the "more specialized for N != 0" version B<N, int>, preferring it to the "more generic" version B<N, void>.
If I understand the confusion, when you see /* primary class template B */ template <int N, class = void> struct B : std::false_type {}; /* partial specialization of B */ template <int N> struct B<N, std::enable_if_t<(N != 0), int>> : std::true_type {}; You think that when the compiler sees B<1> in main, it sees that the general template is ok, then it goes to see the specialization and sees that (N != 0) is true, resolves std::enable_if_t<(N != 0), int> to int thus resulting in B<1, int>, which is good and to be preferred since it is a specialization. The story is slightly different. The line template <int N, class = void> just means, as suggested in a comment, that when you write B<an-int> the compiler sees B<an-int, void>. If you look at it from this perspective, you should see why the mismatch causes the behavior you observe: B<1> is just B<1, void>, and no specialization is targeting that.
70,055,737
72,158,332
Is constrained auto cast valid?
Since C++20, the constrained auto is introduced by: Concept auto identifier = init Which means, for instance: std::integral auto x = 10; is valid. Also, for new-expressions, concept is allowed to be paired with auto: new Concept auto { expr }; // or: new Concept auto ( expr ); auto{expr} or auto(expr) was introduced in C++23 as roughly equivalent to: auto __temp { expr }; return __temp; Does it mean that Concept auto { expr } or Concept auto ( expr ) is also valid? The simple use case would be usable in trying to create a decay copy while checking its operations checked by constraint.
[dcl.spec.auto.general]/5 allows only auto to be the simple-type-specifier of a functional type conversion, even though a constrained placeholder-type-specifier can be a simple-type-specifier grammatically.
70,055,751
70,055,946
Given n positive integer numbers.Print how many numbers occurs at least 2 times in this array on C++
Input: 4 1 2 2 3 Output: 1 Hello guys! There is one problem...I planned to make this through a map, but... `#include <iostream> #include <map> using namespace std; int main(){ int n; cin >> n; int arr[n]; map<int,int> m; map<int,int> :: iterator it = m.begin(); for(int i = 0;i < n;i++){ cin >> arr[i]; it = m.find(arr[i]); if(*it == m.size()); } return 0; }` ProblemC.cpp:15:26: note: 'std::pair<const int, int>' is not derived from 'const std::multimap<_Key, _Tp, _Compare, _Alloc>' if(*it == m.size()); ^ I don't even know how to properly solve this, please help me Here is a photo with more details
I am assuming that in if statement you want to check if find algorithm returned end of map. Better way to do it is to try to insert value into map and check operation return value. You should change it to: if (!m.insert({arr[i], 1}).second) { counter++; }
70,055,752
70,056,866
insert method for doubly linked list C++
I am implementing doubly linked list in C++, and I have been trying to make my insert method work without success. The class should contain two node pointers: one to the head of the list, and one to the tail of the list. If the list is empty, they should both point to nullptr. The insert method should take a value at given index and add it to the list, increasing its size with one element. my code is: #include <iostream> #include <vector> using namespace std; struct Node { int value; Node *next; Node *prev; //previous node pointer Node(int v) : value(v), next(nullptr), prev(nullptr) {} }; class LinkedList { private: Node *head; Node *tail; Node *prev; Node *get_node(int index) { if (index < 0 or index >= size) { throw range_error("IndexError: Index out of range"); } Node *current = head; for (int i = 0; i < index; i++) { current = current->next; } return current; } public: int size; LinkedList() { head = nullptr; tail = nullptr; } int length() { Node *current = head; int count = 0; while (current != nullptr) { count++; current = current->next; } cout << "Length of list is " << count << endl; return count; } void append(int value) { Node *new_node = new Node(value); if (head == nullptr) { head = new_node; head->prev = nullptr; new_node->next = tail; } else if (tail == nullptr) { tail = new_node; new_node->next = nullptr; } } void print() { Node *current = head; Node *prev; cout << "["; if (current->next == NULL) { cout << current->value; cout << "]"; } else { while (current->next != nullptr) { cout << current->value; cout << ", "; prev = current; current = current->next; } cout << current->value << "]" << endl; } } ~LinkedList() { Node *current; Node *next; current = head; while (current != nullptr) { next = current->next; delete current; current = next; } } int &operator[](int index) { return get_node(index)->value; } void insert(int val, int index) { Node *current = new Node(val); Node *prev = get_node(index - 1); Node *next = current->next; prev->next = current; } }; int main() { LinkedList a; a.append(1); // Appending elements to list a.append(2); a.append(3); a.append(4); a.append(5); a.print(); // [1, 2, 3, 4, 5] a.insert(3, 1); a.print(); }; This gives me the error libc++abi.dylib: terminating with uncaught exception of type std::range_error: IndexError: Index out of range Abort trap: 6
I tried to fix all of your methods, probably succeded, at least current test example is printing correct answer: Try it online! #include <iostream> #include <vector> using namespace std; struct Node { int value; Node *next; Node *prev; //previous node pointer Node(int v) : value(v), next(nullptr), prev(nullptr) {} }; class LinkedList { private: Node *head; Node *tail; Node *get_node(int index) { if (index < 0) throw range_error("IndexError: Index out of range"); Node *current = head; for (int i = 0; i < index; i++) { if (!current) break; current = current->next; } if (!current) throw range_error("IndexError: Index out of range"); return current; } public: LinkedList() { head = nullptr; tail = nullptr; } int length() { Node *current = head; int count = 0; while (current != nullptr) { count++; current = current->next; } cout << "Length of list is " << count << endl; return count; } void append(int value) { Node *new_node = new Node(value); if (head == nullptr) { head = new_node; tail = head; } else { tail->next = new_node; new_node->prev = tail; tail = new_node; } } void print() { Node *current = head; cout << "["; if (current->next == NULL) { cout << current->value; cout << "]"; } else { while (current->next != nullptr) { cout << current->value; cout << ", "; current = current->next; } cout << current->value << "]" << endl; } } ~LinkedList() { Node *current; Node *next; current = head; while (current != nullptr) { next = current->next; delete current; current = next; } } int &operator[](int index) { return get_node(index)->value; } void insert(int val, int index) { Node *node = new Node(val); if (index == 0) { if (!head) { head = node; tail = head; } else { node->next = head; head->prev = node; head = node; } } else { Node *prev = get_node(index - 1); Node *next = prev->next; prev->next = node; node->prev = prev; node->next = next; if (next) next->prev = node; if (prev == tail) tail = node; } } }; int main() { LinkedList a; a.append(1); // Appending elements to list a.append(2); a.append(3); a.append(4); a.append(5); a.print(); // [1, 2, 3, 4, 5] a.insert(3, 1); a.print(); }; Output: [1, 2, 3, 4, 5] [1, 3, 2, 3, 4, 5]
70,055,969
70,055,986
erase() in list does not work in c++ on MacOS. What is bash: line 1: 88225 Segmentation fault: 11?
#include <iostream> #include <list> using namespace std; int main () { list<int> mylist; list<int>::iterator it; for(int i=1;i<6;i++){ mylist.push_back(i); } for (it=mylist.begin(); it!=mylist.end(); ++it) cout << ' ' << *it; cout<<endl; for(it=mylist.begin(); it!=mylist.end();it++){ if((*it)==2){ mylist.erase(it); mylist.insert(it,9); break; } } for (it=mylist.begin(); it!=mylist.end(); ++it) cout << ' ' << *it; cout<<endl; return 0; } It seems that mylist.erase(it) is not working because when I delete it, the program works. The output for the above program is 1 2 3 4 5 bash: line 1: 88370 Segmentation fault: 11 "/Users/alimtleuliyev/Desktop/quiadratic" [Finished in 441ms with exit code 139]
You need to write if((*it)==2){ it = mylist.erase(it); mylist.insert(it,9); break; } To output the list it is better to use the range-based for loop. Also to find an element in the list with the given value it is better to use the standard algorithm std::find instead of using a for loop. Here is a demonstration program. #include <iostream> #include <list> #include <iterator> #include <algorithm> int main() { std::list<int> mylist; for ( int i = 1; i < 6; i++ ) { mylist.push_back( i ); } for (const auto &item : mylist) { std::cout << item << ' '; } std::cout << std::endl; auto it = std::find( std::begin( mylist ), std::end( mylist ), 2 ); if ( it != std::end( mylist) ) { it = mylist.erase( it ); mylist.insert( it, 9 ); } for (const auto &item : mylist) { std::cout << item << ' '; } std::cout << std::endl; return 0; } The program output is 1 2 3 4 5 1 9 3 4 5 Pay attention to that instead of calling the member functions erase and insert you could just write if ( it != std::end( mylist) ) *it = 9;
70,056,043
70,056,136
How to kill a process with QProcess::execute()?
I've some problems with killing a process using taskkill. My code: QStringList args; args << "/F"; args << "/IM testApp.exe"; QProcess::execute("taskkill", args); //Should be 'taskkill /IM testApp.exe /F' Output (translated from german): ERROR: Invalid argument - "/IM testApp.exe". Type "TASKKILL /?" to show the syntax.
"/IM testApp.exe" makes a single arg, but should be two args. You get the command taskkill /F "/IM testApp.exe". The proper invocation is QStringList args; args << "/F"; args << "/IM"; args << "testApp.exe"; QProcess::execute("taskkill", args);
70,056,246
70,056,420
VS2019 explicit specialization requires template<> error with 'using' keyword
I have this piece of c++ code, and VS2019 to compile it: #include <iostream> template<typename t> class c { }; int main(){ using o = class c<int>; } does anybody know why it does not compile, complaining about: Error C2906 'c<int>': explicit specialization requires 'template <>' With mingw-gcc it compiles and runs without error. Here you can compare compiler outputs: https://godbolt.org/z/55fMzh8qz Thanks in advance.
class is unnecessary in the using statement, I think visual studio thinks you are trying to declare a specialisation of c: template <> class c<int>; hence the error message. All you need is: using o = c<int>;
70,056,539
70,056,716
Disable class template member for void types?
Considering the following basic class template: #include <type_traits> template < typename T > class A { public: A() = default; T obj; template < typename U = T, typename = typename std::enable_if< !std::is_void< U >::value >::type > T& get(); }; I'm using <type_traits> to get a simple SFINAE implementation that hides get() if template argument is void. However, I still get the compiler error for void types error: forming reference to void, which I am not sure the reasons for are. Is there anything wrong with the class declaration syntax? int main(int argc, char const *argv[]) { A<int> b; A<void> t; // error: forming reference to void return 0; } EDIT: It was pointed out that the issue was that obj can't be void. One workaround would be to use a pointer instead: #include <type_traits> #include <memory> template < typename T > class A { public: A() = default; std::shared_ptr< T > obj; template < typename U = T, typename = typename std::enable_if< !std::is_void< U >::value >::type > U& get() { return *obj; }; }; But I still get the error: forming reference to void, which implies that the compiler is still trying to compile get().
The first problem is that you are trying to define a variable using T obj; where T is void. But according to documentation Any of the following contexts requires type T to be complete: definition of an object of type T; But since void is incomplete type, you get the error: error: 'A::obj' has incomplete type Second we also can't have a return type of void& which is why you get the error you mentioned: error: forming reference to void You can solve it by: #include <type_traits> #include <iostream> template < typename T > class A { public: A() = default; T *obj = nullptr;//note a pointer template < typename U = T> typename std::enable_if<!std::is_same<U, void>::value,U&>::type get() { std::cout <<"called"<<std::endl; if(obj != nullptr) { std::cout<<"not null"<<std::endl; return *obj; } else { std::cout<<"null"<<std::endl; obj = new T{}; return *obj; } } ~A() { std::cout<<"destructor called"<<std::endl; if(!std::is_same<T, void>::value) { std::cout<<"deleted"<<std::endl; delete obj; obj = nullptr; } else { std::cout<<"not deleted"<<std::endl; } } }; int main(int argc, char const *argv[]) { A<int> b; std::cout<< b.get() <<std::endl;//this will print the string "called" and the integer 0 on console std::cout<<"------------------"<<std::endl; int &p = b.get(); std::cout<<"------------------"<<std::endl; p = 32; std::cout << b.get()<<std::endl; std::cout<<"------------------"<<std::endl; A<void> t; return 0; } Also, don't forget to use delete in the destructor.
70,056,563
70,057,084
Wy can't I cast a statically cast Lambda as a TIMEPROC Function pointer in a settimer?
I coded this multiple times. But it doesn't even seem to work in a simple console hello word application. Is hWND the one to blame, lambda, or the casting of the lambda? void sleeper() { Sleep(10000); } int main() { SetTimer (GetConsoleWindow(), 1, 1000, [](HWND, UINT, UINT_PTR, DWORD) { printf("Hello World!"); } ); sleeper(); return 0; } It doesn't give me warnings.
You cannot cast a lamba to a TIMEPROC* or any other type of function pointers that use a different calling convention than the default (one can not specify the calling convention of a lambda). Lambdas are callable objects. This type is similar to a class, with a member function. Aside from that, you MUST use the correct declaration for yout TIMERPROC hook. It is: // definition from the MS website. It is incomplete (typical from MS) // ref: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nc-winuser-timerproc void Timerproc( HWND unnamedParam1, UINT unnamedParam2, UINT_PTR unnamedParam3, DWORD unnamedParam4 ) // the actual definition from winuser.h. typedef VOID (CALLBACK* TIMERPROC)(HWND, UINT, UINT_PTR, DWORD): // note the use of CALLBACK, which expands to __stdcall. That's the very important // detail missing from the actual documentation. You can declare your timeproc as a free-standing function, or as a static member function of a class, Unfortunately the onluy parameter you can pass to the callback is a HWND, this means that if you want to pass any extra parameter to your callback, you have to use static (aka global) variables. Example 1. void CALLBACK myTimerProc(HWND, UINT, UINT_PTR, DWORD) { printf("Hello World!"); } int main() { // NOTE nIDEvent, the timer ID has to be unique for the window and NON-ZERO, // See MS documentation here: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-settimer SetTimer(GetConsoleWindow(), 1, 1000, myTimerProc); sleeper(); return 0; } Example2, if you want to define locally: int main() { struct local // or any other { static void CALLBACK timerProc(HWND, UINT, UINT_PTR, DWORD) { printf("Hello World!"); } } SetTimer(GetConsoleWindow(), 1, 1000, local::timerProc); sleeper(); return 0; } EDIT: For reference, the actual parameters for the TIMERPROC callback. Source: http://www.icodeguru.com/VC%26MFC/MFCReference/html/_mfc_cwnd.3a3a.settimer.htm void CALLBACK EXPORT TimerProc( HWND hWnd, // handle of CWnd that called SetTimer UINT nMsg, // WM_TIMER UINT nIDEvent // timer identification DWORD dwTime // system time );
70,056,750
70,056,817
Why don't const l-value references to r-values result in dangling references?
Why is the following not an error? const auto& foo = std::string("foo"); In my mental model of C++ I think of references as glorified non-null pointers that the language wraps in syntactic sugar for me. However the code below would be an error but the above is not. const auto* foo = &(std::string("foo")); In the reference case why is the string not immediately destructed after the r-value expression is evaluated?
Because this is the language rule Lifetime of a temporary Whenever a reference is bound to a temporary or to a subobject thereof, the lifetime of the temporary is extended to match the lifetime of the reference. There is no such rule for const pointers.
70,056,960
70,057,189
SSH to port exposed by container - permission denied
I have a docker container running and it's exposing port 22 to local host port 1312. I am using the following command to run the container: docker run -it -d -p 127.0.0.1:1312:22 -v /workspace/project:/root --name cpp_dep cpp_dep Now to build the project in CLion, it need to be able to ssh into the container. I entered the container in interactive mode and ran "service ssh restart". Now when I try to ssh into root@127.0.0.1:1312, it asks for my password. But when I enter my sudo (root) password, it keeps saying permission denied. Is it an issue with ssh key? Which password should i use? or is there any way to bypass the password? I am running a MAC OS. Thanks in advance.
You may enter the container in interactive mode, use whoami to find the current user while use passwd to change the password of current user, then ssh into it using the updated passwd. More details if you are interested: User running the container is decided by USER config in your Dockerfile: https://docs.docker.com/engine/reference/builder/#user -u option in docker run command: https://docs.docker.com/engine/reference/run/#user By default it's root (uid = 0), but it depends on your settings. User password is stored in /etc/passwd file, which is different inside the container and in the host, so the same uid may have different password inside the container. It's a workaround to mannually reset it using passwd in the interactive mode but your may also set it in Dockerfile like RUN echo 'root:Docker!' | chpasswd // (NOTICE: unsafe!) It changes the password for root as "Docker!" EDIT #1 As emphasized by David Maze in comments, it's unsafe to store plain password in the Dockerfile as it's public to anyone who get the source file, and it's not uncommon source files intended to be private mistakenly submitted to open github repository. If the container needs to provide public service, you must use build args (https://docs.docker.com/engine/reference/commandline/build/#set-build-time-variables---build-arg) so password can be secretly specified at build time. Dockerfile: ARG PASSWD RUN echo 'root:${PASSWD}' | chpasswd build: docker build --build-arg PASSWD=<secret stored safely>
70,056,975
70,057,004
Array index loop to begin instead of mem access error
I'm currently developping a vision system which is controlled/moonitored via a computer application that I'm writting in C/C++. If you are wondering why I,m writting in C/C++ its basically that my vision sensor (LMI Gocator 2490) has functions developped in C and that I'm using opencv (C++) to analyse its data. Long story short, I've had 1 informatics course which was in C and I'm bad at C++. I'm wondering if there is a simple way, using or writting a function for example, to retrieve an array index that loops back to its begining instead of trying to read write in an index that isn't part of the array which also causes mem access violation. For example: long a[4]; for (size_t i = 0; i < sizeof(a) / sizeof(long); i++) { if (a[i] && a[i + 1]) //Define some conditions regarding a[i] and a[i+1] { //Process code } } So here, its easy to understand that when i will reach the value of 3, I will get mem access violation. What I would like to do, is to have some sort of mecanism which would return a array index that "looped" back to begining. In the case shown above, i+1 where i = 3 would be 0. If I were to put i+2, I would like to get 1, and so on... This might be silly but it would save me the pain of writting 4 times the same logic in some switch/case statement inside a for-loop which then I'd need to apply modifications in all the 4 logics when debugging... Thank's!
use modulus to wrap when reaching the upper bound long a[4]; size_t sz = sizeof(a) / sizeof(long); for (size_t i = 0; i < sz; i++) { if (a[i] && a[(i + 1) % sz]) //Define some conditions regarding a[i] and a[i+1] { //Process code } } maybe not super-optimal performance wise, though (well, with a value of 4, the compiler can trade modulus for mask so it would be okay). In the general case, avoid a division, and check if overruns then choose 0 if it does for (size_t i = 0; i < sz; i++) { size_t j = i < sz-1 ? i+1 : 0; if (a[i] && a[j]) //Define some conditions regarding a[i] and a[i+1] { //Process code } } (the code will work in C and C++)
70,057,205
70,237,776
Is it possible to get something similar to std::next_permutation, but doesn't always use all the letters in the string?
I currently have this code void get_permutations(std::string s, std::vector<std::string>& vec) { std::sort(s.begin(), s.end()); do { vec.push_back(s); } while (std::next_permutation(s.begin(), s.end())); } and it works as intended, but next_permutation uses every character in s, and I would like to simply get every single combination of every character inside the string. (no duplicates) example: input: abc output: a, b, c, ab, ac, abc, acb, etc Is there another standard method for this or would I have to make my own?
Yes, there is more or less a standard approach. Counting and bit masking will be used. If you have some permutation of 3 letters, like "abc", then we will create bit masks like the following: 1. 001 --> "--c" 2. 010 --> "-b-" 3. 011 --> "-bc" 4. 100 --> "a--" 5. 101 --> "a-c" 6. 110 --> "ab-" 7. 111 --> "abc" You see, we simply count up, starting from 1 up to 2^(length of string). Then, for each set bit, we select one letter from the original current permutation of the string. Since you do want only unique combinations, we use a std::set to eliminate duplicates. Somehow simple . . . One of many many possible solutions could be: #include <algorithm> #include <string> #include <iostream> #include <vector> #include <set> std::vector<std::string> get_permutation(std::string s) // Yes, pass by value, make a copy { std::set<std::string> result{}; // Here we will store the result as set std::sort(s.begin(), s.end()); // Sort input string in order to get permutations do { for (size_t k = 1; k < (1 << s.length()); ++k) { // Count and mask std::string combination = {}; // Here wewill stor all possible combinations for (unsigned int m{1}, i{}; m < (1 << s.length()); m <<= 1, i++) if (k & m) combination += s[i]; // Add letter, if bit mask is set result.insert(combination); // Add new combination. Std::set will make it unique } } while (std::next_permutation(s.begin(), s.end())); // And the next 3 letter permutation return { result.begin(), result.end() }; // Return result as vector } int main() { std::string s = "abc"; for (const std::string& c : get_permutation(s)) std::cout << c << '\n'; }
70,057,408
70,057,527
Recursive Function to Iterative Function
//Binary Search Tree #include <iostream> #include "BinaryNode.h" using namespace std; template <class V> class BinaryTree { BinaryNode<V> *root; int nodeCount; public: BinaryTree(); //BinaryTree(const V& newValue); bool isEmpty() const; int getHeight() const; int _getHeight(BinaryNode<V>*) const; int getNumberOfNodes() const; V getRootData() const; void setRootData(const V&); bool add(const V&); bool remove(const V&); BinaryNode<V>* _remove(const V&, BinaryNode<V>*); BinaryNode<V>* getInOrderSuccessor(BinaryNode<V>*); void clear(); bool contains(const V&) const; bool _contains(BinaryNode<V>*, const V&) const; //print tree void printPreorder() const; void _printPreorder(BinaryNode<V> *curr) const; //void printInorder() const; //void printPostorder() const; }; template<class V> BinaryTree<V>::BinaryTree(){ root = nullptr; nodeCount = 0; } /* template<class V> BinaryTree<V>::BinaryTree(const V& newValue){ root = new BinaryNode<V>(; objCount++; } */ template<class V> bool BinaryTree<V>::isEmpty() const { return root == nullptr; } template<class V> int BinaryTree<V>::getHeight() const { return _getHeight(root); } template<class V> int BinaryTree<V>::_getHeight(BinaryNode<V>* curr) const{ if (curr != nullptr) { int lHeight = _getHeight(curr->getLeftChildPtr()); int rHeight = _getHeight(curr->getRightChildPtr()); return ((lHeight > rHeight) ? lHeight + 1 : rHeight + 1); } else return 0; } template<class V> int BinaryTree<V>::getNumberOfNodes() const { return nodeCount; } template<class V> V BinaryTree<V>::getRootData() const { if (!isEmpty()) { return root->getValue(); } } template<class V> void BinaryTree<V>::setRootData(const V& newValue) { root->setValue(newValue); } template<class V> bool BinaryTree<V>::add(const V& newValue) { // Adds a node cout << "adding node..." << endl; BinaryNode<V> *curr = root; if (!isEmpty()) { return _add(newValue, curr); } else { BinaryNode<V> *temp = new BinaryNode<V>(newValue); root = temp; nodeCount++; return true; } } For my class assignment, we were told to take the add function and change it from recursive to iterative. Does anybody have any suggestions on how I could do this? We are supposed to keep the function the same, but we are able to change its definition. This is just a short snippet of the whole code, but I don't think the rest is needed for this.
You can start with a while loop and 2 pointers like this: BinaryNode<V> *curr = root; BinaryNode<V> *prev; if (!isEmpty()) { while(curr) //while current is not null { prev=curr; if(newValue>curr->getValue()) { curr=curr->right; } else { curr=curr->left; } } if (newValue>prev->getValue()) { prev->right=newValue; } else { prev->left=newValue; } } the getValue() function is the one used in getRootData() to get the data of current node that is being pointed. I took help from here Also, its a good practice to google the actual problem first and then come to stack overflow if you don't find a satisfying answer.