# NUCLEAR RABBIT

Member

540

318 Neutral

• Rank
1. ## Bubble Sort Algorithm Review

Thank you, I appreciate the help! :D I like your suggestions
2. ## Bubble Sort Algorithm Review

Hello!   So I wanted to create a bubble sort algorithm and I have it working properly, I was just wondering if anyone could take a look at my code and give me any advice/suggestions on making it more efficient or if I did anything I should avoid doing. I would really appreciate any tips! I know that typically the bubble sort algorithm shouldn't print out each pass thru or maybe it shouldn't display anything at all, but I just wanted to add those print statements for testing purposes and so that I could see that the algorithm was working properly /////////////////////////////////// // // // Bubble Sort Algorithm // // --------------------- // // // // Bubble Sort Algorithm // // using C++ // // // // Date: 5/12/16 // // // /////////////////////////////////// #include <iostream> #include <string> #include <vector> #include <iterator> //========================================================================================== template <typename T> void displayList(std::vector<T> theList) { if (theList.size() == 0) std::cout << "*** Cannot display empty list ***\n\n"; else { int counter = 1; std::vector<T>::iterator listIter; for (listIter = theList.begin(); listIter != theList.end(); listIter++) { // checks if a comma should be placed after an item if (listIter != theList.end()) { if (counter == theList.size()) std::cout << *listIter << "\n"; else std::cout << *listIter << ", "; } counter++; } } } //========================================================================================== template <typename T> void bubbleSort(std::vector<T> & theList) { if (theList.size() == 0) { std::cout << "BubbleSort Begin:\n" << "----------------------------\n" << "| *Error: List is empty\n" << "----------------------------\n\n"; } else { bool sorted = false; bool altered_list; int passthru_counter = 1; int counter = 0; std::vector<T>::iterator listIter; std::cout << "Intial List Order: "; displayList(theList); std::cout << "\nBubbleSort Begin:\n-------------------------------------------------\n"; while (sorted == false) { counter = 0; altered_list = false; for (listIter = theList.begin(); listIter != theList.end(); listIter++) { // if the list was stepped thru and no items were out of place if (counter + 1 < theList.size()) { if (theList[counter] > theList[counter + 1]) { T temp = theList[counter]; theList[counter] = theList[counter + 1]; theList[counter + 1] = temp; altered_list = true; std::cout << passthru_counter << " pass thru:\t"; displayList(theList); passthru_counter++; break; } else counter++; } else { if (altered_list == false) { sorted = true; break; } } } } std::cout << "-------------------------------------------------\n"; std::cout << "*** The list is sorted\n"; std::cout << "*** # of pass thrus to sort = " << passthru_counter << "\n"; std::cout << "-------------------------------------------------\n\n"; } } //========================================================================================== int main() { std::vector<std::string> testList; // test values testList.push_back("lol"); testList.push_back("omg"); testList.push_back("wtf"); testList.push_back("kek"); testList.push_back("btw"); testList.push_back("fyi"); bubbleSort(testList); system("PAUSE"); return 0; }
3. ## Memory Allocation

lol       You're right, that is an issue. However, I dont think thats it will solve this particular issue with my program though because when I call pop(), I make sure the function is not empty so return NULL isnt ever called. I even tried changing return NULL to return -1 and the same issue happened. Everything is working properly with no crash up until I add the free(temp) statement in the pop() method. If I uncomment that statement, it works perfect besides the fact that the memory leak isnt solved when popping.   Will node solve your issue but FYI, the correct solution in this case is quite simple: template<typename T> T returnDefault(void) { return T(); } This will return a specified default value for all types (int = 0, T* = nullptr, custom type = default-ctor, ...), so just replace return NULL by return T() and you should be fine in this regard.     Thank you, I never learned this       Yes, this is the problem, you should be calling malloc(sizeof(struct Node)) .   However, you can make life easier using new and delete, like this // in push() Node* temp = new Node;   // later, in pop() delete temp; And, I just noticed, in pop(), why are you calling malloc() on temp again, then immediately assigning temp to headNode?  Don't malloc temp in pop().   You need to understand memory allocation a little more, then you should be able to tackle this problem fine.     Yeah I def needed to learn about memory allocation more haha I looked up some tutorials and watched some video explanations and I think I am understanding it better now.     PS - Thank you to everyone that helped me out, I got it working now!
4. ## Memory Allocation

thanks, I totally forgot about that condition. No luck solving the heap corruption though :unsure:       You're right, that is an issue. However, I dont think thats it will solve this particular issue with my program though because when I call pop(), I make sure the function is not empty so return NULL isnt ever called. I even tried changing return NULL to return -1 and the same issue happened. Everything is working properly with no crash up until I add the free(temp) statement in the pop() method. If I uncomment that statement, it works perfect besides the fact that the memory leak isnt solved when popping.   Main.cpp ////////////////////////////////// // // // Data Structures - Queues // // ------------------------ // // // // Creating a queue system // // using linked lists and // // C++ (FIFO) // // // ////////////////////////////////// #include "LibIncludes.h" void displayQueueSize(Queue<int> queue) { std::cout << "Queue Size = " << queue.getSize() << "\n\n"; } int main() { Queue<int> myQueue; myQueue.push(2); myQueue.push(3); myQueue.push(5); displayQueueSize(myQueue); int removed = myQueue.pop(); if (removed < 0) std::cout << "\n*** pop() was unsuccessful. Queue is empty.\n"; else std::cout << "\n*** pop() was successful. " << removed << " was removed.\n"; system("PAUSE"); return 0; } Queue.h #pragma once template <class T> class Queue { public: Queue(); Queue(T newItem); void push(T newItem); void pop_all(); T pop(); T peek(); bool isEmpty(); int getSize(); private: struct Node { T data; Node * nextNode; }; Node LinkedList; Node * headNode; // front of the queue Node * tailNode; // End of the Queue int size; }; #include "Queue.inl" Queue.inl #include "LibIncludes.h" template <typename T> Queue<T>::Queue() { headNode = nullptr; tailNode = nullptr; size = 0; std::cout << "*** A new empty Queue was created ***\n\n"; } /////////////////////////////////////////////////////////////////////////////// template <typename T> Queue<T>::Queue(T newItem) { Node * temp = (struct Node *)malloc(sizeof(struct Node *)); temp->data = newItem; temp->nextNode = nullptr; headNode = temp; tailNode = temp; size = 1; std::cout << "*** A new Queue with starting item " << headNode->data << " was created ***\n\n"; } /////////////////////////////////////////////////////////////////////////////// template <typename T> bool Queue<T>::isEmpty() { if (headNode == NULL) return true; else return false; } /////////////////////////////////////////////////////////////////////////////// template <typename T> T Queue<T>::peek() { if (isEmpty()) return NULL; else return headNode->data; } /////////////////////////////////////////////////////////////////////////////// template <typename T> void Queue<T>::pop_all() { if (isEmpty()) std::cout << "pop_all() was used, but the Queue is already empty.\n\n"; else { std::cout << "pop_all() was used and destroyed the Queue.\n\n"; Node temp = headNode; for (int i = 0; i < size; i++) { pop(); } headNode = nullptr; tailNode = nullptr; size = 0; } } /////////////////////////////////////////////////////////////////////////////// template <typename T> void Queue<T>::push(T newItem) { Node * temp = (struct Node *)malloc(sizeof(struct Node *)); temp->data = newItem; temp->nextNode = nullptr; if (isEmpty()) { headNode = temp; tailNode = temp; } else { tailNode->nextNode = temp; tailNode = temp; } size++; std::cout << "push() was called and " << newItem << " was added to the Queue.\n\n"; } /////////////////////////////////////////////////////////////////////////////// template <typename T> T Queue<T>::pop() { if (isEmpty()) { std::cout << "pop() was used, but the Queue is empty.\n\n"; return -1; } else { Node * temp = (struct Node *)malloc(sizeof(struct Node *)); temp = headNode; T removedItem = headNode->data; headNode = headNode->nextNode; std::cout << "pop() was used and " << temp->data << " was removed from the Queue.\n"; free(temp); temp = nullptr; size--; if (size == 0) { free(tailNode); tailNode = nullptr; } return removedItem; } } /////////////////////////////////////////////////////////////////////////////// template <typename T> int Queue<T>::getSize() { return size; }
5. ## Memory Allocation

yes isEmpty() is working correctly and yes the objects are created using malloc.       which portion were you referring to?
6. ## Memory Allocation

Hello,   So I am editing a project I had where I was creating a queue. In my pop() method I am having an issue and I am not sure why. I am trying to free the memory of the Node I am popping from the queue and also returning the data from that Node to the user before it is deleted. When I comment out the free() method in the pop() method it works and when I uncomment the free() call I get heap memory crashes. Can anyone please help me see what I am doing wrong?   Queue.inl template <typename T> T Queue<T>::pop() { if (isEmpty()) { std::cout << "pop() was used, but the Queue is empty.\n\n"; return NULL; } else { Node * temp = headNode; T removedItem = temp->data; headNode = headNode->nextNode; std::cout << "pop() was used and " << temp->data << " was removed from the Queue.\n\n"; free(temp); size--; return removedItem; } } Queue.h #pragma once template <class T> class Queue { public: Queue(); Queue(T newItem); void push(T newItem); void pop_all(); T pop(); T peek(); bool isEmpty(); int getSize(); private: struct Node { T data; Node * nextNode; }; Node LinkedList; Node * headNode; // front of the queue Node * tailNode; // End of the Queue int size; }; #include "Queue.inl"
7. ## Data Structures Help!

Yeah, I had to change those as well. The & always slips my mind :rolleyes: haha
8. ## Data Structures Help!

Thanks! I was not aware of having to do this with templates!         Thanks a lot! I used the .inl file method and it worked great!

10. ## C++ Deleting data from files

You're right, I did not even think about crashes during the copying/writing to the file!     Very interesting, I did not know that about fstream, thanks for all the useful information!
11. ## C++ Deleting data from files

Hello,   I finished writing a Phonebook application today, I just wanted to practice dealing with writing/reading/handling data from external files. All went well and the application works just like I want it too, but I was just wondering if my implementation is "the correct" way of for deleting specific portions of txt files. I wrote the function 2 different ways, one by creating a vector filled with Person objects that contains info from the contact list and I use those to fill the contact list file and the other way (which is commented out) was done by writing to a tmp txt file with the data minus what I want to delete and write over the original file with whats in the tmp file. I didn't like this way because I had the tmp contact file list lingering around.   Any advice on the proper way of handling this type of task or if you know a better way please let me know! Thanks! void Phonebook::deleteEntry() { int selection; bool valid = false; do { displayAllEntries(); if (num_of_contacts < 1) break; std::cout << "\n\n\t\t\t\t\tEnter in the Entry to delete (0 = Cancel): "; std::cin >> selection; valid = std::cin.good(); // making sure the selection was an int value if (!valid) { std::cin.clear(); std::cin.ignore(INT_MAX, '\n'); } else { // checks if user has contacts to delete and if the selection // is in range if ((selection <= num_of_contacts) && (num_of_contacts > 0) && (selection != 0)) { std::vector<Person> contacts; std::ifstream reader("ContactList.txt", std::ios::in); if (reader.is_open()) { // read data from ContactList and create Persons // to fill the fill the file after deletion // ignores the selected contact std::string fname, lname, email, phone_number; for (int i = 0; i < num_of_contacts; i++) { reader >> fname >> lname >> email >> phone_number; // i is always 1 less than the actual selection number if ((i + 1) != selection) contacts.push_back(Person(fname, lname, email, phone_number)); } num_of_contacts--; reader.close(); } else { std::cout << "\n\n\t\t\t\t\t*** [ Error! Cannot Open Contact List ] ***"; std::cout << "\n\t\t\t\t\t"; system("PAUSE"); } std::ofstream writer("ContactList.txt", std::ios::out); if(writer.is_open()) { // Fills the file with the data from the contact vector for (int i = 0; i < num_of_contacts; i++) { writer << contacts[i].getFirstName() << " " << contacts[i].getLastName() << " " << contacts[i].getEmail() << " " << contacts[i].getNumber() << std::endl; } std::cout << "\n\n\t\t\t\t\t----------------------------"; std::cout << "\n\t\t\t\t\t| Deletion Successfull |"; std::cout << "\n\t\t\t\t\t----------------------------"; writer.close(); } else { std::cout << "\n\n\t\t\t\t\t*** [ Error! Cannot Open Contact List ] ***"; std::cout << "\n\t\t\t\t\t"; system("PAUSE"); } // FILE READING/WITING TO TMP FILE IMPLEMENTATION /*std::ifstream reader("ContactList.txt", std::ios::in); std::ofstream writer("tmp_contacts.txt", std::ios::out); if (reader.is_open()) { std::string fname, lname, email, phone_num; for (int i = 1; i <= num_of_contacts; i++) { if (i != selection) { reader >> fname >> lname >> email >> phone_num; writer << fname << " " << lname << " " << email << " " << phone_num << std::endl; } else { reader >> fname >> lname >> email >> phone_num; } } num_of_contacts -= 1; reader.close(); writer.close(); writer.open("ContactList.txt", std::ios::out); reader.open("tmp_contacts.txt", std::ios::in); for (int i = 1; i <= num_of_contacts; i++) { reader >> fname >> lname >> email >> phone_num; writer << fname << " " << lname << " " << email << " " << phone_num << std::endl; } std::cout << "\n\n\t\t\t\t\t----------------------------"; std::cout << "\n\t\t\t\t\t| Deletion Successfull |"; std::cout << "\n\t\t\t\t\t----------------------------"; } else { std::cout << "\n\n\t\t\t\t\t*** [ Error! Cannot Open Contact List ] ***"; std::cout << "\n\t\t\t\t\t"; system("PAUSE"); }*/ } else if (selection == 0) { std::cout << "\n\n\t\t\t\t\t-----------------------------------------"; std::cout << "\n\t\t\t\t\t| Canceling Request To Delete Entry |"; std::cout << "\n\t\t\t\t\t-----------------------------------------"; } else { valid = false; std::cout << "\n\n\t\t\t\t\t*** [ Error! Invalid Selection ] ***"; std::cout << "\n\t\t\t\t\t"; system("PAUSE"); } } } while ((!valid) && (num_of_contacts != 0)); }
12. ## C++ Class Constructor

I just changed all the items in the std namespace to have the prefix std:: and that for some reason solved everything. Weird, there was no issues in Person.h, but that std:: issue caused other things to show up as an error
13. ## C++ Class Constructor

I have no idea why, but I converted everything to 'std::' and removed the using namespace and that solved my issue! So weird how it was that tat was causing trouble   Thanks to everyone who tried to help me as well! I researched most vexing parse and I learned something new!
14. ## C++ Class Constructor

Hello,   So I am working on a simple phonebook app using file reading/writing, but in my Phonebook class constructor I am having issues. For some reason it is not allowing me to pass a string argument to the constructor. I took out the argument in the definition and declaration and it compiled fine and ran so I know that is where the issue is.   The error message is "C2664    'Phonebook::Phonebook(Phonebook &&)': cannot convert argument 1 from 'std::string' to 'const Phonebook &'    MyPhonebook    c:\users\brandon\documents\visual studio 2015\projects\myphonebook\myphonebook\main.cpp    30" and it doesn't make any sense to me. I googled the error message and I am passing a string to the constructor not any other type. I also get another error message saying "C4430    missing type specifier - int assumed. Note: C++ does not support default-int    MyPhonebook    c:\users\brandon\documents\visual studio 2015\projects\myphonebook\myphonebook\person.h    14"   Can someone please help me see what is happening? I would greatly appreciate it!   Phonebook.h #pragma once #include "LibIncludes.h" class Phonebook { public: Phonebook(string tmp_pb_name); void addEntry(); void deleteEntry(); void searchByFirstName() const; void searchByNumber() const; void displayAllEntries() const; void clearAllEntries(); int mainMenu(); private: string phonebook_name; }; Phonebook.cpp /////////////////////////////////////// // // Phonebook definitions // /////////////////////////////////////// #include "LibIncludes.h" Phonebook::Phonebook(string tmp_pb_name) { phonebook_name = tmp_pb_name; } //-------------------------------------------------------------------- int Phonebook::mainMenu() { int option = 0; do { system("CLS"); cout << "\n\n\t\t-----" << phonebook_name << " Phonebook-----"; cout << "\n\t\t|"; cout << "\n\t\t|\t[1] Create New Entry"; cout << "\n\t\t|\t[2] Delete Entry"; cout << "\n\t\t|\t[3] Display ALL Entries"; cout << "\n\t\t|\t[4] Search By FIRST Name"; cout << "\n\t\t|\t[5] Search by PHONE NUMBER"; cout << "\n\t\t|\t[6] Clear ALL Entries"; cout << "\n\t\t|\t[7] Exit Your Phonebook"; cout << "\n\t\t|----------------------------------------------"; cout << "\n\n\t\t> "; cin >> option; if (option < 1 || option > 7) { cout << "\n\t\t*** [ Error! Option Out Of Range! ] ***\n"; system("PAUSE"); } } while (option < 1 || option > 7); return option; } //-------------------------------------------------------------------- void Phonebook::addEntry() { } //-------------------------------------------------------------------- void Phonebook::displayAllEntries() const { } //-------------------------------------------------------------------- void Phonebook::clearAllEntries() { } //-------------------------------------------------------------------- void Phonebook::deleteEntry() { } //-------------------------------------------------------------------- void Phonebook::searchByFirstName() const { } //-------------------------------------------------------------------- void Phonebook::searchByNumber() const { } Main.cpp /////////////////////////////////////// // // Basic phonebook app that // uses writing and reading // from files for the data // entries // ////////////////////////////////////// #include "LibIncludes.h" string setPhoneBookName() { string name; cout << "\n\n\n\n\t\t\t\t-----Please Enter In Your Desired Phonebook Name-----"; cout << "\n\t\t\t\t> "; cin >> name; return name; } //--------------------------------------------------------------------------------------- int main() { int user_option = 0; bool exit = false; Phonebook myBook(setPhoneBookName()); while (user_option != 7) { while (!exit) { user_option = myBook.mainMenu(); switch (user_option) { case 7: cout << "\n\n\t\t---------------Goodbye---------------\n"; cout << "\t\t"; system("PAUSE"); exit = true; break; default: cout << "\n*** [ Invalid Option! ] ***\n"; } } } return 0; } LibIncludes.h ///////////////////////////////////// // // All header files needed // ///////////////////////////////////// #pragma once #include <iostream> #include <string> #include <fstream> #include "Person.h" #include "Phonebook.h" using namespace std;
15. ## C++ VirtualFunctions [SOLVED]

thanks for the help!