How to list all elements in a stack in c++ [duplicate] - c++

In c++ how can I print out the contents of my stack and return its size?
std::stack<int> values;
values.push(1);
values.push(2);
values.push(3);
// How do I print the stack?

You could make a copy of the stack and pop items one-by-one to dump them:
#include <iostream>
#include <stack>
#include <string>
int main(int argc, const char *argv[])
{
std::stack<int> stack;
stack.push(1);
stack.push(3);
stack.push(7);
stack.push(19);
for (std::stack<int> dump = stack; !dump.empty(); dump.pop())
std::cout << dump.top() << '\n';
std::cout << "(" << stack.size() << " elements)\n";
return 0;
}
Output
19
7
3
1
(4 elements)
See it live here: http://liveworkspace.org/code/9489ee305e1f55ca18c0e5b6fa9b546f

The only way to print the elements of a std::stack without popping them, is to write an adapter that extends std::stack (here's an example). Otherwise, you should replace your stack with a std::deque.

Both std::stack and std::queue are wrappers around a general container. That container is accessible as the protected member c. Using c you can gain efficient access to the elements; otherwise, you can just copy the stack or queue and destructively access the elements of the copy.
Example of using c:
#include <iostream> // std::wcout, std::endl
#include <stack> // std::stack
#include <stddef.h> // ptrdiff_t
using namespace std;
typedef ptrdiff_t Size;
typedef Size Index;
template< class Elem >
Size nElements( stack< Elem > const& c )
{
return c.size();
}
void display( stack<int> const& numbers )
{
struct Hack
: public stack<int>
{
static int item( Index const i, stack<int> const& numbers )
{
return (numbers.*&Hack::c)[i];
}
};
wcout << numbers.size() << " numbers." << endl;
for( Index i = 0; i < nElements( numbers ); ++i )
{
wcout << " " << Hack::item( i, numbers ) << endl;
}
}
int main()
{
stack<int> numbers;
for( int i = 1; i <= 5; ++i ) { numbers.push( 100*i ); }
display( numbers );
}

http://www.cplusplus.com/reference/stl/stack/
for the size it's easy use :
cout << mystack.size();
For the rest i didn't see anything about in the doc but you should print the content of your stack when you push it, or have a list with it to keep a record of the element just in order to print it, don't forget to delete it when you're done testing

Related

Passing arrays to functions in c++ code error

I am learning C++, and I cannot figure out why this code outputs the right number of outputs (4), but only output the number 54. Can someone help fix it and explain what I did wrong?
#include <iostream>
using namespace std;
void pi(int arr[],int x){
for(int c = 0;c < x;c++){
cout << arr[x] << endl;
}
}
int main()
{
int _arr[4] = {3543,146,961262,-242};
pi(_arr, 4);
}
You are confusing the array limit with the indexer. Should be:
cout << arr[c] << endl;
Arrays are zero indexed. You are trying to print out the element that is out of bounds thus invoking undefined behaviour. Depending on the platform your output might look like four 0 or something like -858993460. By convention counter variables usually start with the letter i.
Since x is 4, arr[x] is arr[4]. But _arr only has four entries, it doesn't have a fifth entry. So you are outputting garbage. You probably meant arr[c] in the loop.
Change
cout << arr[x] << endl;
To
cout << arr[c] << endl;
There is a typo in the loop inside the function
for(int c = 0;c < x;c++){
cout << arr[x] << endl;
^^^
}
There should be
for(int c = 0;c < x;c++){
cout << arr[c] << endl;
^^^
}
It is the variable c that serves as an index in the array.
Nevertheless the program has several drawbacks.
You should not use identifiers starting with an underscore. Such names can be reserved by the compiler implementation.
Do not use "magic numbers". They are usually serve as a reason for bugs.
To store sizes of objects or arrays use the type size_t instead of the type int.
The function does not change the array. So the corresponding parameter should be declared with the qualifier const.
The program can look the following way
#include <iostream>
void pi( const int arr[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
std::cout << arr[i] << std::endl;
}
}
int main()
{
int arr[] = { 3543, 146, 961262,-242 };
pi( arr, sizeof( arr ) / sizeof( *arr ) );
}
Take into account that you could output the array using a standard algorithm as for example std::for_each or std::copy.
Here is a demonstrative program that uses the standard algorithm std::copy to output the array.
#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
int arr[] = { 3543, 146, 961262,-242 };
std::copy( std::begin( arr ),
std::end( arr ),
std::ostream_iterator<int>( std::cout, "\n" ) );
}

Reverse array with recursion C++

My main idea is to shrink they array from both sides . For example if the input is 1234 , wanna print 1234 and then 4321 (the reversed) .
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
int reversedArray(int* x)
{
cout<< "*x out of while =" << *x <<endl ;
while( *x != 0 )
{
cout << "*x=" << *x << endl;
cout<< "====================== im in reversed =================" << endl ;
return reversedArray( x+1 );
}
cout<< "after return " << *x << endl;
}
int main ()
{
int Array[] = {10,2,3,4,8 ,0} ;
int* p_Array = Array;
reversedArray( Array );
}
After the "while" , why the functions that are in the stack, do not return to the next line ( " the --> cout<< "after return " <<*x <
void printReversed(int * x)
{
if (*x == 0) return;
std::cout << *x;
printReversed(x+1);
std::cout << *x;
}
The line:
return reversedArray( x+1 );
exits the function. So you never repeat the while or execute any of the code after the while if you go into the while. This makes the while effectively an if statement.
The code posted by Crazy Eddie does the job and Barmar explains the ineffectiveness of the while loop. I decided to post a non-recursive way to address the problem mentioned.
#include <iostream>
#include <vector>
using namespace std;
vector<int> reverseArray(vector<int>& arr) {
vector<int> ans;
int n = arr.size();
// insert all elements in the reverse order
for (size_t i = 0; i < n; i++) {
ans.push_back(arr[n-i-1]);
}
return ans;
}
int main ()
{
int array[] = {10, 2, 3, 4, 8, 0};
// convert into vector
vector<int> arr(array, array+6);
vector<int> rev = reverseArray(arr);
// merging the 2 arrays
arr.insert(arr.end(), rev.begin(), rev.end());
// printArray(arr) -- implement to fit your needs;
}
When you pass an int[] to a function it decays to an int* which is simply an address in memory. C++ a better plan would be to use copy_backward with an ostream_iterator:
copy_backward(Array, Array + sizeof(Array) / sizeof(*Array), ostream_iterator<int>(cout, " "))
Note that this method uses the actual size of the array, and does not depend upon a terminal element. Thus, no numbers are offlimits, and it's impossible to segfault by failing to provide the terminating element.
If you have access to C++11 you can simplify that a bit further to:
copy(crbegin(Array), crend(Array), ostream_iterator<int>(cout, " "))
Live Example

How to make a list C++ [closed]

So I have to make a program that stores input piece by piece, until -1 is input. An example of this input would be 1 1 1 0 3 5 3 -1. And -1 would not be recorded. Then it plays the list back to you, but bacwards, so output would be 3 5 3 0 1 1 1
To do this I need to make a list of objects, but I have no clue how to declare them, or how to add/remove items to them. how do I do this?
You need a place to store values that can grow as values are read.
The simpler is probably std::vector, but also std::list or std::deque as well as whatever bidirectional container will do the game.
Then you need a loop to get the values an save them into the container (the push_back method has that purpose), and another loop getting the values from the container from the end and printing them.
This can be done using iterators or using indexes, depending on the container and on your own specific needs.
This may be a possibility:
#include <vector>
#include <iostream>
template<class V, class S>
void read_numbers(V& v, S& s, N end)
{
N x=0;
while(x << s)
{
if(x==end) return;
v.push_back(x);
}
std::cerr << "error: bad reading" << std::endl;
}
template<class V, class S>
void write_numbers(const V& v, S& s)
{
for(auto i=s.rbegin(); i!=s.rend(); ++i)
std::cout << *i << ' ';
std::cout << std::endl;
}
int main()
{
std::vector<int> nums;
read_numbers(nums, std::cin, -1); }
write_numbers(nums, std::cout);
return 0;
}
For a list of unknown size, you can declare a vector class:
std::vector<int> myVector;
Then to add an element, use push_back:
// assign some integer to myInt
myVector.push_back (myInt);
http://www.cplusplus.com/reference/vector/vector/push_back/
If you need to use a list, then you could use std::list.
You can declare them like this:
std::list<int> myList;
You can read more about std::list here.
You can use it for inspiration.
#include <vector>
#include <iostream>
int main(int argc, char * argv[]) {
std::vector<int> numbers;
int number;
do {
std::cin >> number;
if (number != -1) {
numbers.push_back(number);
}
} while(number != -1);
for (std::vector<int>::reverse_iterator it = numbers.rbegin(); it != numbers.rend(); ++it) {
std::cout << *it << " ";
}
std::cin.get();
return 0;
}
As was suggested already, you could use std::vector. It resizes as you push more elements. If the requirement is strictly a linked list, then go for std::list.
As to the requirement of playing them in reverse order, just use reverse_iterator and go through the list printing them.
std::list<int> mylist;
// Insert the elements.
for (std::list<int>::reverse_iterator rIt = mylist.rbegin();
rIt != mylist.rend(); ++rIt) {
cout << *rIt;
}
There are basically two options:
You can use a pointer int *data and manually allocate memory to it with new[]. You'll need to continually reallocate the array as you find that the array is larger than you expected.
You can use one of the wonderful containers that c++ provides. I might suggest std::vector.
Here's an example of how you might implement this:
#include <iostream>
#include <vector>
int main() {
std::vector<int> data;
while (true) {
int number;
std::cin >> number;
if (!std::cin)
break;
if (number == -1)
break;
data.push_back(number);
}
for (int datum : data)
std::cout << datum << " ";
std::cout << "\n";
}

Sorting alphabetically from file with numerical placeholder

I have a list that I need to sort alphabetically, while that is the case I also need to keep their original position as the list is initially listed chronologically. I've got the list sorting in alphabetic order, I have no idea how to add in the chronological position.
Any ideas?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("prez.dat");
ofstream fout("sorted.dat");
void main()
{
//fin.open("prez.dat");
//fout.open("sorted.dat");
vector<string> names;
if(!fin.is_open())
{
cout << "Unable to open file..." << endl;
}
string word;
while(getline(fin, word))
names.push_back(word);
sort(names.begin(), names.end());
for (size_t i=0; i <names.size(); i++)
cout << names[i] << '\n';
system("pause");
}//End of void main()
EDIT: What I'm looking for:
The file looks like this:
Apple
Orange
Banana
What I'm needing is this:
Apple 1
Banana 3
Orange 2
One way to approach this is to keep both the input string and the original ordinal position together in an object. Then sort based on solely the string portion of the object and then emit both strings and original ordinal position for each object.
For example for your class you could have this:
class MyData {
private:
std::string s; // the string read from the file
unsigned ord; // original position of the string
public:
// standard constructor
MyData(std::string str, unsigned order) : s(str), ord(order) {}
// this allows you to use "std::cout << md;"
friend std::ostream& operator<<(std::ostream& out, const MyData &m) {
return out << m.s << ' ' << m.ord;
}
static bool cmp(const MyData &a, const MyData &b) {
return a.s < b.s;
}
};
Then all you need is to create and push the objects and to define a comparison operation for use with std::sort. See this reference for details and an example of how to do that part.
Here's one way to do that:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
// MyData code goes here
int main(int argc, char *argv[]) {
if (argc < 2) {
std::cout << "Usage: sortfile filename\n";
return 0;
}
std::vector<MyData> vec;
std::string line;
int i=1;
for(std::ifstream in(argv[1]); std::getline(in, line); ++i)
vec.push_back(MyData(line, i));
std::sort(vec.begin(), vec.end(), MyData::cmp);
std::cout << "vec contains:\n";
for (auto md : vec)
std::cout << md << '\n';
}
When compiled (as C++11), from this input file which I called fruit.txt:
Apple
Orange
Banana
Using the file ./sorted fruit.txt gives this result:
vec contains:
Apple 1
Banana 3
Orange 2
I'm not sure that I understand what you exactly want. But I guess you need to know the chronological position for every element in the sorted vector.
If your question is that, the answer is too easy. you can just make a new int victor that has the same length of your victor (10 for example) and contain list of numbers from 1 to the 10. When you sort your victor you have to make changes on your victor. Now just do the same changes on the numbers victor, so you can know the time of each element.
example:
big, car, app
1, 2, 3
when you sort them they will be like that:
app, big, car
3, 1, 2
but in this way u cant use this function to sort u must write it by yourself.
If your compiler supports lambda functions, you can use one for the compare:
// sort vector by index using lambda compare function
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
int main()
{
std::vector <std::string> names;
std::vector <size_t> index;
std::string fruits[5] = { "peach", "cherry", "apple", "plum", "banana" };
for(size_t i = 0; i < sizeof(fruits) / sizeof(fruits[0]); i++){
names.push_back(fruits[i]);
index.push_back(i);
}
std::sort(index.begin(), index.end(), [&names](size_t i, size_t j)
{return names[i] < names[j];});
for(size_t i = 0; i < names.size(); i++){
std::cout << "names[" << std::setw(2) << index[i] << "] = " <<
names[index[i]] << std::endl;
}
return 0;
}
If your compiler doesn't support lambda functions, you can sort a vector of iterators to a vector of strings:
// sort vector of strings by vector of iterators to vector of strings
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
bool compare_strings_by_iterator(
std::vector <std::string>::iterator i,
std::vector <std::string>::iterator j)
{
return *i < *j;
}
int main()
{
std::vector <std::string> names;
std::vector <std::string>::iterator it;
std::vector <std::vector <std::string>::iterator> itv;
std::string fruits[5] = { "peach", "cherry", "apple", "plum", "banana" };
for(size_t i = 0; i < sizeof(fruits) / sizeof(fruits[0]); i++)
names.push_back(fruits[i]);
for(it = names.begin(); it < names.end(); it++)
itv.push_back(it);
std::sort(itv.begin(), itv.end(), compare_strings_by_iterator);
for(size_t i = 0; i < names.size(); i++)
std::cout << "name [" << std::setw(2) << itv[i] - names.begin() <<
"] " << *itv[i] << std::endl;
return 0;
}

How can I print out the contents of std::stack and return its size?

In c++ how can I print out the contents of my stack and return its size?
std::stack<int> values;
values.push(1);
values.push(2);
values.push(3);
// How do I print the stack?
You could make a copy of the stack and pop items one-by-one to dump them:
#include <iostream>
#include <stack>
#include <string>
int main(int argc, const char *argv[])
{
std::stack<int> stack;
stack.push(1);
stack.push(3);
stack.push(7);
stack.push(19);
for (std::stack<int> dump = stack; !dump.empty(); dump.pop())
std::cout << dump.top() << '\n';
std::cout << "(" << stack.size() << " elements)\n";
return 0;
}
Output
19
7
3
1
(4 elements)
See it live here: http://liveworkspace.org/code/9489ee305e1f55ca18c0e5b6fa9b546f
The only way to print the elements of a std::stack without popping them, is to write an adapter that extends std::stack (here's an example). Otherwise, you should replace your stack with a std::deque.
Both std::stack and std::queue are wrappers around a general container. That container is accessible as the protected member c. Using c you can gain efficient access to the elements; otherwise, you can just copy the stack or queue and destructively access the elements of the copy.
Example of using c:
#include <iostream> // std::wcout, std::endl
#include <stack> // std::stack
#include <stddef.h> // ptrdiff_t
using namespace std;
typedef ptrdiff_t Size;
typedef Size Index;
template< class Elem >
Size nElements( stack< Elem > const& c )
{
return c.size();
}
void display( stack<int> const& numbers )
{
struct Hack
: public stack<int>
{
static int item( Index const i, stack<int> const& numbers )
{
return (numbers.*&Hack::c)[i];
}
};
wcout << numbers.size() << " numbers." << endl;
for( Index i = 0; i < nElements( numbers ); ++i )
{
wcout << " " << Hack::item( i, numbers ) << endl;
}
}
int main()
{
stack<int> numbers;
for( int i = 1; i <= 5; ++i ) { numbers.push( 100*i ); }
display( numbers );
}
http://www.cplusplus.com/reference/stl/stack/
for the size it's easy use :
cout << mystack.size();
For the rest i didn't see anything about in the doc but you should print the content of your stack when you push it, or have a list with it to keep a record of the element just in order to print it, don't forget to delete it when you're done testing

Resources