2

New to standard library containers and my teacher asked a question like this at the end of lecture today for us to learn them

Write a C++ program that reads int from standard input until the end of a file and then prints them in reverse order--one per line. Use the standard library containers to store the data. No use of the new operator.

How would I do this if I had to use the standard library containers?

int main()
int i = 0;
{int array[];

vector<int> integers (array, array+ array.size)
for (i=0; i<array.size, i++) 
   cin>>a[i];

vector<int>::const_reverse_iterator reverse iterator;

^^this is my pseudocode so far, still getting there. Any feedback?

  • you can try std::vector, std::list etc... – fatihk Nov 25 '14 at 07:00
  • You should get yourself a good reference for those libraries, for example: http://en.cppreference.com/w/ Using the "STL" isn't hard. – user1942027 Nov 25 '14 at 07:02
  • 7
    Congratulations to your teacher for teaching their students to use the standard library. – Shoe Nov 25 '14 at 07:02
  • C++ is case sensitive, so don't use NEW; instead, use new if anything. – kdog Nov 25 '14 at 07:03
  • 8
    @Jefffrey Also congratulations for actually forbidding `new`. That keyword should not appear in everyday code anymore, IMO. – Chnossos Nov 25 '14 at 07:21
  • 1
    This isn't the site to ask us to do your work for you. Recommended reading: [What's this STL vs. “C++ Standard Library” fight all about?](https://stackoverflow.com/questions/5205491/whats-this-stl-vs-c-standard-library-fight-all-about) –  Nov 25 '14 at 07:22
  • @Jefffrey Is it not a commonly taught topic anymore? – user3819671 Nov 25 '14 at 07:24
  • @Chnossos - I'm curious as to why not. Is there a reason why one should not return an instance of an object from a function? In the case that there is not, how else would you suggest returning said object without it going out of scope when the function ended? :curious: – enhzflep Nov 25 '14 at 07:27
  • 1
    You do this by reading up on the different standard library containers and algorithms and writing some code. – juanchopanza Nov 25 '14 at 07:27
  • 1
    @enhzflep You return the object by value. – juanchopanza Nov 25 '14 at 07:30
  • 1
    @Chnossos It's just as much cargo culting to forbid new as it is to encourage it. Without understanding why `new` is bad, the OP is just as clueless as they were before. –  Nov 25 '14 at 07:30
  • 1
    @enhzflep Nowadays (since C++11 or even C++0x) we simply use smart pointers and STL Containers returned by value, and let the compiler move the memory around for us. – Chnossos Nov 25 '14 at 07:33
  • 1
    @user3819671 The problem is the other way around. Teachers kept teaching the old way using `new` and doing manual memory management leading to students never learning the more modern and easy way to do it, using the facilities already provided by the STL. That said it's still helpful understanding the manual way if you really need it, but tbh that should be teached after the students are already familiar with the easy STL way. – user1942027 Nov 25 '14 at 07:34
  • @RaphaelM. I was taught the manual way prior to STL so I am curious to know how I would feel about STL if I had learned the manual way after. STL was introduced to us just today so I still feel very overwhelmed by it. Im hoping coding small things like this program will help cement the concept behind it. – user3819671 Nov 25 '14 at 07:45
  • Back to the question... I suggest you have a look at Mateusz's answer, then try to change the output loop to use your `const_reverse_iterator`... you'll need to use `rbegin()` and `rend()`. A quick google should provide you with examples. You don't need any `int array[]` nor `int i`. Try to start with the very simplest things and keep the program compiling. Use 'std::cout << xyz << std::endl;' to output variables as your program runs, so you can verify it is doing what you expect, for example - output `integers.size()` to see the vector size increasing. – Tony Delroy Nov 25 '14 at 08:00

2 Answers2

4

I cannot speak for others but I think that careless usage of the acronym "STL" is intellectually dishonest. If you want to refer to the "C++ standard library", then say so. The abbreviation can mean many different things, including the standard library, the original STL implementation (which is over a decade old), or any of its ports. For more reading, see What's this STL vs. “C++ Standard Library” fight all about?

In terms of learning C++, many students seem to neglect one of the most important (and very expensive) resources they have, which is their school. If you have a problem, always ask your teacher first. Ask the teacher's aide. Ask other students. Find an on-campus tutor. Hit the library. If your library doesn't have a book you want, request that it be delivered to your campus. But I'll give you the benefit of the doubt and assume you have done that already.

If you want a reference, try cppreference. For a beginner, it is not very easy to parse, although it considerably simplifies the language from the standard. If you want a tutorial, try any one of Bjarne Stroustrup's million of books (exaggeration). The C++ Programming Language (4th Edition) is a good choice. The ISO C++ website also lists popular compilers, online compilers and a small list of books by C++ personalities (Herb Sutter, Scott Meyers, etc.) There is also Marshall Cline's C++-faq (various authors).

People also seem to forget that StackOverflow is a resource. People have spent hundreds of hours contributing to the , and even just sorting C++ questions by votes gives plenty of high quality content to go through. If that isn't enough, sort the user page by reputation and look for users who are experts in C++ and read their questions and answers. You can't say that you haven't been able to find the answer to your problem after doing all that.

Nothing I have wrote so far constitutes an answer to the question, so let's tackle your problem.

Your current code shows:

int main()
int i = 0;
{
  int array[];

  vector<int> integers (array, array+ array.size)
  for (i=0; i<array.size, i++) 
     cin>>a[i];

  vector<int>::const_reverse_iterator reverse iterator;

The first issue is your K&R style declaration. int i = 0 needs to inside main. Then, you have an array of unknown bound. In this context, it is not allowed. Just start off with a std::vector, an array isn't needed here. And finally, you don't need a reverse_iterator and I'll show you why in a second.

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v;
    int current_num;
    while (std::cin >> current_num)
        v.push_back(current_num); 
}

This idiom, std::cin >> current_num, is useful because it's concise and the loop will exit gracefully (i.e., bad user input or EOF). Please see Why is iostream::eof inside a loop condition considered wrong? for a longer explanation.

Now you want to print the integers in reverse order. You have three ways of doing this:

std::sort(v.rbegin(), v.rend());
std::reverse(v.begin(), v.end()); // #include <algorithm>

Then loop through and print each element. Or use a loop that iterates through the vector backwards while printing each element. The two methods above are virtually equivalent, but I included rbegin() because it returns a reverse iterator, demonstrating that you don't have to deal with a naked iterator.

I won't bother to provide longer explanations because it's 3:30 in the morning but hopefully that will get you started. Good luck.

0

If you are starting, best is std::vector.

vector<int> v;
int temp = 0;

while(cin>>temp)
{
    v.push_back(temp);
}

for(int i=0; i<v.size(); i++)
    cout<<v[v.size()-1-i] <<endl;
  • People may argue about whether it's good to provide a complete solution for homework, but downvoting this is a bit harsh - especially as it's from a new user.... +1 – Tony Delroy Nov 25 '14 at 07:46
  • @TonyD But there are simpler ways to iterate over the elements of a vector in reverse order. This is error prone and unnecessary. Good advice would be "have a look at what vector can do for you". This answer doesn't even follow that basic advice. – juanchopanza Nov 25 '14 at 08:02
  • 1
    @juanchopanza Yes, I know that, but when You see someone is starting to learn new topic and asks about very simple topics, it is not good answer to provide too complicated response. First things first. Learn about vector, then move into more advanced topics (like iterators) after testing some basic functionalities. This is my opinion. – MateuszZawadzki Nov 25 '14 at 08:06
  • @MateuszZawadzki Whether this is less complicated than using iterators is arguable. It is certainly less safe. – juanchopanza Nov 25 '14 at 08:10
  • @juanchopanza: " less complicated than using iterators is arguable" - I agree - arguable both ways - so I'd say Mateusz's answer's not unreasonable and a useful comment would be "but do consider reverse iterators once you've got this working" (as I recommended in a comment directly on the question 30 minutes ago). It's easy enough for people to accidentally dereference `end()` or `rend()` or compare a `reverse_iterator` to `end()` accidentally that I don't consider the "less error prone" argument compelling. – Tony Delroy Nov 25 '14 at 08:34