I started writing this code a few days ago. I saw a question on here that got me wondering about variable argument lists, so I wrote (never really finished, but it has the functionality I was curious about) this piece of code:
void VendingMachine::setStamps(int largest, ...)
{
cout << "Setting stamps to: \n";
vector<int> tmp;
vector<int>::iterator iter;
int next = largest;
va_list lst;
va_start(lst, largest);
while(next != NULL)
{
cout << next << "\n";
tmp.push_back(next);
next = va_arg(lst,int);
}
va_end(lst);
stamps = new int[tmp.size()-1];
int i = 0;
for(iter = tmp.begin(); iter != tmp.end();)
{
stamps[i] = *iter;
iter++;
i++;
}
cout << "The array is now: ";
showStamps();
}
void VendingMachine::showStamps()
{
cout << sizeof(stamps) << " " << sizeof(*stamps);
for(int i = 0; i < NUM_OF(stamps); i++)
cout << stamps[i] << ", ";
cout << "\n";
}
Now, what I'd expect is for setStamps to never finish. Or at least take a very long time, and a variable amount of time, since no part of the list is guaranteed to be NULL unless it was supplied. This isn't the case. I call setStamps with v.setStamps(90,30,24,15,12,10,5,3,2,1); and it prints this out:
Setting stamps to:
90
30
24
15
12
10
5
3
2
1
-217832717
The array is now: 4 490,
Ignoring the last line, since that was me messing around trying to figure out how to determine the length of an array, this doesn't make sense. It stopped after the first value that was outside of the passed arguments. It should have kept going until there was a NULL value, and there shouldn't be one of those in the same place each time. But the outcome is always the same: 90, 30, 24, 15, 12, 10, 5, 3, 2, 1, [number that changes each time]. There's never any additional values. It's a mystery.
and there shouldn't be one of those in the same place each time
Who says there won't be one in the same place every time? The behavior is undefined, and so having a NULL value in the same place every time is entirely possible.
Related
So I have a stack example I created following a tutorial using the stack library
stack<string> custs;
custs.push("george");
custs.push("louie");
custs.push("florence");
// cout << "size" << custs.size() << endl;
if (!custs.empty()) {
for (int i = 0; i <= custs.size(); i++) {
cout << custs.top() << endl;
custs.pop();
}
}
I ran this and got the output:
florence
louie
My question is why isn't it outputting George as well? The program outputs the top data then pops it. This means it should output Gorge then pop it after. Why doesn't this happen? initially the code was i < cust.size so I thought because i is not less than 1 it would not ouput. So I switched it to <= and it still doesn't output George. How come?
It is because you are both increasing i and reducing the size of the stack in the loop.
You can rewrite your loop like this:
while (!custs.empty()) {
cout << custs.top() << endl;
custs.pop()
}
Here is a step by step explanation of what is happening so you can understand it better:
First, i starts as 0, and custs.size() returns 3. Since 0 <= 3 is true, the body of the loop executes, printing "florence" and removing it from the stack.
On the second iteration, i equals 1, and custs.size() returns 2, because you had 3 items but you removed one. Since 1 <= 2 is true, the body of the loop executes again, printing "louie" and removing it from the stack.
Then, i equals 2, and custs.size() returns 1, because you already removed 2 elements. Since 2 <= 1 is false, the body of the loop doesn't execute, and the loop ends.
As you can see, the problem is that your loop's condition changes on each iteration. There are a couple of ways to fix this:
int s = custs.size();
for (int i = 0; i < s; i++) {
cout << custs.top() << endl;
custs.pop();
}
By doing that, you store the original size of the stack, so you can iterate without problems.
Another solution would be to check if the stack is empty on each iteration with a while loop:
while (!custs.empty()) {
cout << custs.top() << endl;
custs.pop();
}
By doing that, you check if there are any elements left to print each time.
Hope this helps!
When you use for loop like this
for (int i = 0; i <= custs.size(); i++) {
cout << custs.top() << endl;
custs.pop();
}
it loops directly till the size of stack which decreases in each iteration.
which in my opinion is the main reason your code is not working. I rewrite this as
int z = custs.size() ;
for(int i=0;i<=z;i++)
{
cout<<custs.top()<<endl;
custs.pop();
}
and it worked perfectly fine. In my opinion, the best approach is to use while loop like this
while(!custs.empty())
{
cout<<custs.top()<<endl;
custs.pop();
}
I already wrote a working project but my problem is, the last part.I have already Read 500.000 row from csv file into vector, then put into the hashtable.I can print whole hashtable but I need to pick top 10 Quantity from my hashtable.Just be clear, I am not about to sort the whole hashtable, just pick top 10.
The topic of my project is,program must be able to store individual products (given with StockCode) from csv file and insert it into a suitable data structure. If that product is already inserted into the structure, its counter must be increased by the quantity of the order.After reading and processing is over, your program must list the “top 10” products ordered by individuals.
There is rule about the libraries, This will be a proper C++ class. You must be able to create many instances of this class. (Please use no third party libraries and C++ STL, Boost etc.) However, you can use, iostream, ctime, fstream, string like IO and string classes.
Important note: Only thing I should focus is speed, storage or size is not a problem.
What I've done so far is,
Read Csv file row by row into vector
Stockcodes in row[1], Quantity in row[3]
Put them into Hashtable and increase their quantity by the quantity of the order.
Print the whole hash table.
What I need to do is,
Print the Top 10 Quantity
Now let's share Example csv file, Driver program codes, Output of the print function.
Csv File look like this:
InvoiceNo;StockCode;Description;Quantity;
536365;85123A;WHITE HANGING HEART T-LIGHT HOLDER;6
536365;71053;WHITE METAL LANTERN;6;
536365;84029G;KNITTED UNION FLAG HOT WATER BOTTLE;6;
536365;84029E;RED WOOLLY HOTTIE WHITE HEART.;6;
536365;22752;SET 7 BABUSHKA NESTING BOXES;2;
536365;21730;GLASS STAR FROSTED T-LIGHT HOLDER;6;
main.cpp
void printMaxQuantity() {
int maxValue=0;
for (int i = 0; i < 1000000; ++i) {
if(table[i] != nullptr) {
if (table[i]->quantity > maxValue)
maxValue = table[i]->quantity;
if (table[i]->quantity == maxValue) {
cout << "Index: " << i << endl;
cout << "StockCode: " << table[i]->stockCode << endl;
cout << "Quantity: " << table[i]->quantity << endl;
cout << endl << endl;
}
}
}
}
};
Here the output:(After edit the code StockCode: 85123A is correct output, but still struggling about the top 10)
Index: 41240
StockCode: 10002
Quantity: 48
Index: 309193
StockCode: 85123A
Quantity: 72
Process finished with exit code 0
Also one last note, I am doing this for a school project so I shouldn't use any third party software or include any different libraries because it is not allowed (I will implement my own vector class later)
Since this is homework, I will avoid writing actual code. Since you do not have any prior information about the actual data set, you will need to loop through it, which is a linear complexity. In order to find the top 10 items I advise you to create an array of 10 items to store the best items you get so far.
The first step is to copy the first 10 elements into your array.
The second step is sort your array of 10 items descendingly, so you will always use the last item for comparison.
Now you can loop the big structure and on each step, compare the current item with the last one of the array of ten elements. If it's lower, then do nothing. If it's higher, then find the highest ranked item in your array of 10 items which is smaller than the item you intend to insert due to higher quality. When you find that item, loop from the end until this item until your array of ten elements and on each step override the curret element with the current one. Finally override the now duplicate element.
Example: Assuming that your 7th element has lower quality than the one you intend to insert, but the 6th has higher quality override 9th element with the 8th, then the 8th with the 7th and then the 7th with the item you just found. Remember that array indexes start from 0.
This is what you want clearly.This code pick the top 10 from your hash table
void hashTable::printTopTen() {
int maxValue = 0;
int indexHolder = 0;
cout << "#" << " " << "Stock Code" << "\t" << "Description" << "\t\t\t" << "Quantity" << endl;
for (int i = 0; i < 10; ++i) { //-> This loop for top 10
for (int index = 0; index < TABLE_SIZE; ++index) { //-> base loop to find max quantity in hash table
if (table[index] != nullptr) { // to check if index is NULL or not
if (table[index]->quantity > maxValue) {
maxValue = table[index]->quantity; //update the maxValue with biggest quantity
indexHolder = index; // -> to store index number of max quantity in hash table
}
}
}
for (int indeX = 0; indeX < TABLE_SIZE; ++indeX) { //find the max quantity's stockCode,description
if (table[indeX] != nullptr) { // to check if index is NULL or not
if (table[indeX]->quantity == maxValue) { //if we have reached the maxValue then it's quantity is top 1
cout << i + 1 << "." << " " << table[indeX]->stockCode << "\t" << table[indeX]->description
<< "\t" << table[indeX]->quantity << endl;
table[indexHolder]->quantity = 0; //after cout the max one, delete the index so it can't be top 1 again
}
}
}
maxValue = 0; // update max value 0 again for second base loop
}
}
This question already has an answer. But I want to show you how to perform selection sort so you can compare it with your code.
**Performance trick: ** Quick Sort algorithm can be used instead of Selection Sort
hashMap=hashTable, hashEntry=Node, so this what I did:
void hashTable::selectionSort() {
int firstCounter, secondCounter;
Node *emptyOne = new Node("empty", "thisEmpty", 0);
Node *temp;
for (firstCounter = 1; firstCounter < TABLE_SIZE; firstCounter++) {
if (table[firstCounter] == nullptr) {
table[firstCounter] = emptyOne;
}
temp = table[firstCounter];
secondCounter = firstCounter - 1;
if (table[secondCounter] == nullptr) {
table[secondCounter] = emptyOne;
}
while (secondCounter >= 0 && table[secondCounter]->quantity > temp->quantity) {
table[secondCounter + 1] = table[secondCounter];
secondCounter = secondCounter - 1;
if (table[secondCounter] == nullptr) {
table[secondCounter] = emptyOne;
}
}
table[secondCounter + 1] = temp;
}
}
My recursive program does not return true when it reaches the specified target, even when it looks like it should. It simply returns false, then terminates, and I can't figure out why.
I've tried to rearrange the order of the If/Else statements in every possible way, I've attempted to debug it using cout, and it looks like it should return true, but it doesn't.
#include <iostream>
using namespace std;
bool isNumberInArray(const int anArray[], int first, int last, int targetNum) {
if (first > last) { //if last number is less than the first number to be searched
return false; //Returns false if the size of the array to be searched is less than the first element of the array
}
if (anArray[last] == targetNum) { //if number at "last" position is equal to the target
return true; //Returns true if the target is found at the last position
}
else { //run again, with last = last - 1
cout << "searching for " << targetNum << "; ran else; position " << last << " value " << anArray[last] << "\n";
//previous line used for testing purposes
isNumberInArray(anArray, first, (last - 1), targetNum);
}
}
int main() {
int numberArray[10] = {1, 2, 3, 11, 5, 6, 7, 8, 9, 10};
if (isNumberInArray(numberArray, 0, 9, 11t))
cout << "True\n";
else
cout << "False\n";
return 0;
}
The program should realistically return "true" when the value of last reaches the position that targetNum is located at, but instead it always returns false, even if it is true, and I can't figure out why. The cout statements that I placed within the function even stop when the program reaches the targetNum, but it still returns false:
searching for 11; ran else; position 9 value 10
searching for 11; ran else; position 8 value 9
searching for 11; ran else; position 7 value 8
searching for 11; ran else; position 6 value 7
searching for 11; ran else; position 5 value 6
searching for 11; ran else; position 4 value 5
False
11 is at position 3.
You need to return the result of your recursive call inside your else clause.
else { //run again, with last = last - 1
cout << "searching for " << targetNum << "; ran else; position " << last << " value " << anArray[last] << "\n";
//previous line used for testing purposes
return isNumberInArray(anArray, first, (last - 1), targetNum);
}
It will return true if the the first item you consult is what you're looking for, however, it will never check further calls of isNumberInArray(), as you never check that value. When the program eventually works it way back up to the first call, it'll enter if (first > last) and return false, when it should in fact be returning the value from isNumberInArray.
I'm working on a project where I need to have the computer print the 12 days of Christmas lyrics. I thought of an idea where I make a FOR loop and have it repeat 12 times. Every time the day changes with the unary operator "++" Here's what I mean:
int main()
{
string Print = first = 1; //Here I want first to become a number so that I can call it up in FOR loop.
cout << "On the first day of Christmas, \nmy true love sent to me\nA partridge in a pear tree.\n" << endl;
for(int loop = 0; loop <= 12; loop++)//This part is a simple for loop, it starts at 0 and goes to 12 until it stops.
{
cout << "On the " << (1,2,3,4,5,6,7,8,9...12) << " day of Christmas,\nmy true love sent to me\n" << endl; HERE!!!!
Here is where I'm having issue. I want the numbers to call in strings to say the day. As in x = 1 will call in "First" and then I can move the number up by using "x++" which will result in x = 2 and then it will say "Second".. all the way to 12. Anyone know how I can resolve this issue?
}
This involves a simple but important part of programming called an array. I don't want to give you the answer directly - you need to use these (or similar structures) all the time, and it is very important to practice their use and understand them. Let's make a simple program using arrays that prints "Hello World":
#include <iostream>
#include <string>
int main() {
std::string words[2]; //make an array to hold our words
words[0] = "Hello"; //set the first word (at index 0)
words[1] = "World"; //set the second word (at index 1)
int numWords = 2; //make sure we know the number of words!
//print each word on a new line using a loop
for(int i = 0; i < numWords; ++i)
{
std::cout << words[i] << '\n';
}
return 0;
}
You should be able to figure out how to use a similar tactic to get the functionality you asked for above. Working Ideone here.
I have three lists and I want to implement a search feature.
How the code works is that I create an iterator that begins at the start of each list and it compares what the user inputs with each and every value in the list, when it finds a match it is supposed to increase an integer variable by one, so in the end it would say:
your value is found: <x amount of times in Example list>
The problem I am having is that it is compiling fine but the end result still gives me 0 like it didn't increment the variable.
I am wondering if it is having trouble comparing the value where the iterator is pointing to the user input, can anyone please shed some light on this? For testing purposes in the
On the iterator search_disregard I manually put 4 identical values in the list, so I know the end result should show me 4, but I still get 0:
cout << "\nSearch for: ";
string edit_search;
cin >> edit_search;
list<string>::iterator search_disregard = disregard_list.begin();
list<string>::iterator search_compare = compare_list.begin();
int search_disregard_count = 0;
int search_compare_count = 0;
for (int x = 0; x < disregard_list.size(); ++x)
{
if (*search_disregard == edit_search)
{
++search_disregard_count;
}
}
for (int x = 0; x < compare_list.size(); ++x)
{
if (*search_compare == edit_search)
{
++search_compare_count;
}
}
cout << edit_tag << edit_search << " is found in the following: \n" << endl;
cout << search_disregard_count << " time(s) in the Disregard List" << endl;
cout << search_compare_count << " time(s) in the Compare List" << endl;
buffer_clear();
You never increment your iterators so they will always point to the first element. The idiomatic way:
for(auto it = container.begin(); it != container.end(); ++it) ...