Overloading << operator for printing stack in c++ - c++

#include <iostream>
#include <ostream>
#include <bits/stdc++.h>
using namespace std;
void printHelper(ostream& os,stack<int>& s){
if(s.empty())
return ;
int val = s.top();
s.pop();
printHelper(s);
os << val << " ";
s.push(val);
}
ostream& operator<<(ostream& os,stack<int>& s){
os << "[ ";
printHelper(os,s);
os << "]\n";
return os;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
stack<int> s;
for(int i = 0;i<5;i++){
s.push(i+1);
}
cout << s;
return 0;
}
// c++ stack -- push pop top size empty
I want to know as to why this code is not working, I want to print my stack in the same fashion as in java within square brackets i.e [ 1 2 3 4 5 ]. Please help me identify what have i done wrong.

The problem(error) is that printHelper expects two arguments but you're passing only when when writing:
//----------v--->you've passed only 1
printHelper(s);
To solve this(the error) just pass the two arguments as shown below:
//----------vv--v---------->pass 2 arguments as expected by printHelper
printHelper(os, s);
Working demo

Related

Trying to print contents of a vector: having trouble with "No operator "<<" matches these operands, operand types are: const char [2] << Card" error

My program is a simple card game. The 'Deck' class is where I am getting the error. I have looked at countless other question to solve it but I just can't. I have already included , and the relevant header files. A few other solutions were way beyond my understanding and said something about using "std::ostream& operator<<(std::ostream& out, const Course& course)", but I have no idea what this is or how to use it. (I'm new to C++). All I'm trying to do is output the contents of a vector. I would really appreciate some help with this.
#include "Deck.h"
#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
Deck::Deck()
{
}
void Deck::shuffle()
{
}
void Deck::setDeck(vector<Card> targetDeck)
{
for (int i = 0; i < deck.size(); i++)
targetDeck.push_back(deck[i]);
// vector<Card> populatedDeck(targetDeck);
}
void Deck::getDeck()
{
}
int Deck::printDeck(vector<Card> cards)
{
std::cout << "Vector contains: ";
for (vector<Card>::iterator it = cards.begin(); it != cards.end(); ++it)
{
cout << (" " << *it);
}
cout << endl;
return 0;
}

How Do I Print a Vector of Tuples?

So I'm trying to make a vector that contains tuples containing two ints, and I'm acquiring the ints from a text file source. To make sure I have the vector I want, I'm trying the print out my contents, but the output is not showing me anything. I'm not sure if it's because of my code, and where I put my text file. I'm just stuck at this point. If anything could help me with this, I'd appreciate it very much. Thanks
using namespace std;
int main()
{
ifstream file("source.txt");
typedef vector<tuple<int, int>> streets;
streets t;
int a, b;
if (file.is_open())
{
while (((file >> a).ignore() >> b).ignore())
{
t.push_back(tuple<int, int>(a, b));
for (streets::const_iterator i = t.begin();i != t.end();++i)
{
cout << get<0>(*i) << endl;
cout << get<1>(*i) << endl;
}
cout << get<0>(t[0]) << endl;
cout << get<1>(t[1]) << endl;
}
}
file.close();
system("pause");
return 0;
Here's my text file and where I placed it
enter image description here
Here's my output from debugging, if that's important
You should use a loop, that will print one tuple at a time.
Complete minimal example:
#include <iostream>
#include <tuple>
#include <vector>
#include <fstream>
using namespace std;
int main(void) {
std::ifstream infile("source.txt");
vector<tuple<int, int>> streets;
int a, b;
while (infile >> a >> b)
{
streets.push_back(tuple<int, int>(a, b));
}
infile.close();
for(auto& tuple: streets) {
cout << get<0>(tuple) << " " << get<1>(tuple) << endl;
}
return 0;
}
Output:
1 2
3 4
5 6
7 8

Removing all the characters (a-z, A-Z) from a string in C++

Here's my code:
#include <iostream>
using namespace std;
string moveString(string t, int index)
{
for (int i=index; t[i]!=NULL;i++)
{
t[i]=t[i+1];
}
return t;
}
string delChars(string t)
{
for (int i=0; t[i]!=NULL; i++)
{
if (t[i]>'a' && t[i]<'z')
{
moveString(t, i);
}
else if (t[i]>'A' && t[i]<'Z')
{
moveString(t, i);
}
}
return t;
}
int main()
{
int numberOfSpaces;
string t;
cout << "Text some word: "; cin>>t;
cout<<delChars(t);
return 0;
}
First function moveString should (in theory) take down every single character from a string by 1 index down (starting from given index) - to remove 1 character. The rest is pretty obvious. But:
Input: abc123def
Output: abc123def
What am I doing wrong?
And a additional mini-question: Acutally, what's the best way to "delete" an element from an array? (array of ints, chars, etc.)
Logic Stuff is right but his answer is not enough. You shouldn't increase i after move. Since the i.th character is removed and i points to the next character now.
string delChars(string t)
{
for (int i=0; t[i]!=NULL; )
{
if (t[i]>'a' && t[i]<'z')
{
t = moveString(t, i);
}
else if (t[i]>'A' && t[i]<'Z')
{
t = moveString(t, i);
}
else
i++;
}
return t;
}
moveString takes t by value and you're not assigning its return value, so it doesn't change t in delChars. So, make sure the next thing you learn are references.
Apart from that, I don't know what to tell about t[i] != NULL (if it is undefined behavior or not), but we have std::string::size to get the length of std::string, e.g. i < t.size(). And if you havet[i + 1], the condition should then be i + 1 < t.size().
Whatever, don't play with it like with char arrays, leaving the string with previous size. You can pop_back the last (duplicate) character after shifting the characters.
It's worth mentioning that it can be done in one line of idiomatic C++ algorithms, but you want to get your code working...
What am I doing wrong?
Not using standard algorithms
Actually, what's the best way to "delete" an element from array? (array of ints, chars, etc.)
By using the standard remove-erase idiom:
#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <cstring>
int main()
{
using namespace std;
auto s = "!the 54 quick brown foxes jump over the 21 dogs."s;
cout << "before: " << quoted(s) << endl;
s.erase(std::remove_if(s.begin(),
s.end(),
[](auto c) { return std::isalpha(c); }),
s.end());
cout << "after: " << quoted(s) << endl;
return 0;
}
expected output:
before: "!the 54 quick brown foxes jump over the 21 dogs."
after: "! 54 21 ."
I'm not allowed to use standard algorithms
Then keep it simple:
#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <cstring>
std::string remove_letters(const std::string& input)
{
std::string result;
result.reserve(input.size());
for (auto c : input) {
if (!std::isalpha(c)) {
result.push_back(c);
}
}
return result;
}
int main()
{
using namespace std;
auto s = "!the 54 quick brown foxes jump over the 21 dogs."s;
cout << "before: " << quoted(s) << endl;
auto s2 = remove_letters(s);
cout << "after: " << quoted(s2) << endl;
return 0;
}

C++ : Turn char array into a string that is printed

just a beginner student learning basic C++. I'm trying to figure out the best way to:
Turn a char array Name of 20 into a string that can be printed.
I found in other Stack Overflow topics to use "str()" such as "str(Name)", but it always comes up 'identifier not found'.
cout << "Name:" << str(Name) << endl;
Set a char array of 20 characters. For some reason, the following gives me errors when declaring. I've tweaked it so many times, but I cannot get why it won't give.
TESCStudent.Name[20] = {'S','u','p','e','r','P','r','o','g','r','a','m','m','e','r','\0'};
Full code I have so far:
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
//Step 1
struct StudentRecord
{
char Name[20];
//Accessor
void printInfo() const;
};
void StudentRecord::printInfo() const
{
cout << "Name:" << str(Name) << endl;
}
int main()
{
//Step 2
StudentRecord TESCStudent;
TESCStudent.Name[20] = {'S','u','p','e','r','P','r','o','g','r','a','m','m','e','r','\0'};
//Step 3
TESCStudent.printInfo();
_getch();
return 0;
}
Given that you are at a very beginner level, just use std::string:
#include <iostream>
#include <conio.h>
#include <string>
struct StudentRecord {
std::string Name;
void printInfo() const {
std::cout << "Name:" << Name << '\n';
}
};
int main() {
StudentRecord TESCStudent;
TESCStudent.Name = "SuperProgrammer";
TESCStudent.printInfo();
_getch();
}
Live demo
The syntax like this:
char Name[20] = {'S','u','p','e','r','\0'};
is used to initialize a variable when you define it. However, in your case,
StudentRecord TESCStudent;
TESCStudent.Name[20] = ...;
You've already defined it on the line before, so you can't "initialize", you have to "assign" it.
This is pretty much why you use std:string instead of char[].

No output when merge function is called

I have a doubt in the following code. Can somebody please explain.
using namespace std;
#define INT_SIZE 32
#define R 4
#define C 4
#define N 4
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
#include<math.h>
#include<limits.h>
#include<stack>
#include<vector>
#include<algorithm>
struct interval{
int start;
int end;
};
bool compareInterval(interval i1, interval i2)
{
return (i1.start < i2.start)? true: false;
}
int merge(vector<interval>& a, int n)
{
stack<interval> s;
sort(a.begin(), a.end(), compareInterval);
s.push(a[0]);
int i=1;
interval temp;
while(i<n)
{
temp = s.top();
s.pop();
if(temp.end > a[i].start && a[i].end > temp.end)
{
temp.end = a[i].end;
s.push(temp);
}
else if(temp.end < a[i].start)
{
s.push(temp);
s.push(a[i]);
}
i++;
}
while(s.size())
{
temp = s.top();
cout << temp.start << " ";
cout << temp.end << "\n";
s.pop();
}
return 0;
}
int main()
{
interval intvls[] = { {6,8}, {1,9}, {2,4}, {4,7} };
vector<interval> intervals(intvls, intvls+4);
for(int i=0;i<4;i++)
{cout << intervals[i].start;
} // This output is not coming when merge function is called
cout << merge(intervals, 4);
}
My doubt is "When I comment the merge function call i.e
// cout << merge(intervals, 4);
When I comment this line, then I am able to see output of cout<<intervals[i].start.
Otherwise, I am not able to see the output.
"
You are not ending your output with a newline. Try:
{cout << intervals[i].start << "\n";}
Without the newline, this output is probably getting hidden amongst all the output produced by merge().
There are few issues with this code.
s.push(a[0]); <-- Only on element is in you stack.
//s.push(a[1]).. you will have to add all other elements like this.
while(i<n)
{
temp = s.top(); <-- for second i s will be empty. Here you must check if stack is empty before getting top element.
s.pop();
}
Your first output is not printed correctly. use std::endl
cout << intervals[i].start << endl;
There is a bug in merge that leads to a segmentation fault. Due to this std::cout is not flushed. If you comment out the line with the merge call, std::cout is flushed when the program exits.