473,698 Members | 2,376 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Stroustrup 5.9 exercise 11

it works fine without any trouble. i want to have advice on improving
the code from any angle like readability, maintenance etc:

---------- PROGRAMME ------------
/* Stroustrup, 5.9, exercise 11

STATEMENT:
Read a sequence of words from the input. use "quit" as the word
to terminate the input. Print the words in the order they were
entered. don't print a word twice.modify the programme to sort the
words before printing them.

*/

#include<iostre am>
#include<string >
#include<vector >

int main()
{
std::vector<std ::stringcollect _input;

std::string input_word;
std::cin >input_word;

for(int i=0; input_word != "quit"; ++i)
{
collect_input.p ush_back(input_ word);
std::cin >input_word;
}

std::cout << "\n *** Printing WOrds ***\n";

for(unsigned int i=0; i < collect_input.s ize(); ++i)
std::cout << collect_input[i]
<< '\n';

return 0;
}

----------- OUTPUT ----------------
[arch@voodo tc++pl]$ g++ -ansi -pedantic -Wall -Wextra -O
ex_5.9-11.cpp
[arch@voodo tc++pl]$ ./a.out
like this
quitting
quite
and morq quotwe FINISHED quiT quit

*** Printing WOrds ***
like
this
quitting
quite
and
morq
quotwe
FINISHED
quiT
[arch@voodo tc++pl]$

Apr 9 '07
27 2440
red floyd wrote:
Ignore my previous post. You forgot std:: on ostream_iterato r. Also,
missing a close paren on std::copy. See embedded.
And the second param to ostream_iterato r constructor is a const char *,
not a char, so it should be "\n"
>
arnuld wrote:
>-------- PROGRAMME --------

#include<iostr eam>
#include<strin g>
#include<algor ithm>
#include<set >
#include<itera tor>

int main()
{
std::string input_word;
std::set<std::s trings; // collects inputs

while(std::cin >input_word && input_word != "quit")
{
s.insert(input_ word);
}
std::cout << "\n *** Printing Sorted Words ***\n";

std::copy(s.beg in(), s.end(),
ostream_iterat or<std::string> (std::cout, '\n');
std::ostream_it erator<std::str ing>(std::cout, '\n'));
> return 0;
}
Apr 10 '07 #21
On Apr 10, 11:05 am, red floyd <no.s...@here.d udewrote:
red floyd wrote:
And the second param to ostream_iterato r constructor is a const char *,
not a char, so it should be "\n"
YES, it works now. i got it:

1.) 1st parameter to "ostream_iterat or" needs to be the stream where i
am sending the output.

2.) 2nd parameter to "ostream_iterat or" must be a string literal.
now from other posts, i conclude:

3.) there are 2 benefits of "std::set" container:

i.) it keeps the items sorted.
ii.) it removes duplication of elements.

4.) "std::copy" container is a generic one and is for maintainability .
e.g if we want to change/modify or make some additions to our
programme like if we want to use a set or list rather than a vector.

thanks

Apr 10 '07 #22
Victor Bazarov wrote:
If performance weren't involved, the scope *is* unnecessariry
wide and the object's construction *is* too soon. That's not
just my opinion. My opinion, however, is that it is impossible
to decide without actually measuring the performance.
Exactly, if the construction of the object is not that though and if the
loop is not too critic, there is often no point in avoid the reiteration
of the construction of the object.

Also, the construction inside the loop often allows you to obey the RAI
paradigm that is not a bad thing.

Actually, in many cases automatic optimization could be done but I don't
know if the compiler is "smart" enough to determine when the constructor
of an object can be called just once instead that in each loop. I don't
think so.

Regards,

Zeppe

Apr 10 '07 #23

"Victor Bazarov" <v.********@com Acast.netwrote in message
news:lI******** *************** *******@comcast .com...
>I think the words "unnecessar ily" and "sooner than" tend
to show a bias.

So, you're saying that by using those words I exposed my bias
towards one of the sides [of the debate]. Had I omitted them,
would the issue actually have been clearer?
No I was just commenting on why you got the reply
that you did. I should have appended a <g>.

In this particular case the wideness of the scope and earlier
construction of the object (both unnecessary by themselves) are
supposedly outweighed by performance of the code, taken apriori.
Sure.
If performance weren't involved, the scope *is* unnecessariry
wide and the object's construction *is* too soon. That's not
just my opinion. My opinion, however, is that it is impossible
to decide without actually measuring the performance.
I would tend to use the more narrow scope and later
construction unless profiling showed it to be a bottleneck.
I've never had this be the case though.
Apr 10 '07 #24
On Apr 9, 12:34 pm, Zeppe <z...@email.itw rote:
arnuld wrote:
it works fine without any trouble. i want to have advice on improving
the code from any angle like readability, maintenance etc:
#include<iostre am>
#include<string >
#include<vector >
It's just a matter of style, but almost anybody puts a space between
#include and the angular parenthesis, because it improves the
readability a lot.
I've also seen a tab there:-).
int main()
{
std::vector<std ::stringcollect _input;
std::string input_word;
std::cin >input_word;
for(int i=0; input_word != "quit"; ++i)
{
collect_input.p ush_back(input_ word);
std::cin >input_word;
}
Here I have two little suggestions. The fist is to eliminate the
repetition of the input reading, the other is that a for cycle should
perform a test that is strictly related on the variable that is being
incremented. If you don't have to iterate in some way through a
sequence, and the test is a little bit particular, it's clearer to write
it without the for.
What displeases me the most here is that he declares an
increments a variable that is never used. It makes me think
that he's forgotten something.

There's also the slight problem that if the user forgets to put
"quit" in the input file, he ends up in an endless loop.
I would prefer in this situation something like:
std::vector<std ::stringcollect _input;
while(true){
std::string input_word;
std::cin >input_word;
if(input_word == "quit")
break;
else
collect_input.p ush_back(input_ word);
}
Which is worse than his original, lying as it does in the
condition, and then hiding a break deap down where no one can
find it. In this case, there is a very easy and idiomatic
solution:

std::vector< std::string collect_input ;
std::string word ;
while ( std::cin >word && word != "quit" ) {
collect_input.p ush_back( word ) ;
}
In this program is pointless to perform such a change, but in bigger
programs is very important to understand very quickly and easily the
meaning of each piece of code.
Even in small programs like this, it's important to handle
incorrect input. (In practice, you'd probably want to make the
check for "quit" case insensitive, but that's not in the
requirements specification for now, and implementing a case
insensitive compare function is not a job for a beginner.)
Another note: if the performances are not a priority, it is better to
declare the variables as close as possible to the point in which they
are used.
The general rule is never to declare a variable until you can
initialize it. Regretfully, the rule doesn't work where input
is involved.
For example, the string "input_word " is not that important in
the whole program, and it's used just in the for. If I'm able to declare
it into the for, I reduce the visibility of the variable to the piece of
code in which I actually use it, and I reduce the chance of error
improving the readability.
I'm not sure I follow. In any real code, I'd split the input
and output out into separate functions, so that the variable
would not be available outside of the function. And since
whether you succeed in reading it is one of the loop conditions,
and you cannot read it unless it has been previously declared,
your stuck declaring it outside the loop.

It's no big deal. The only thing that is a bit bothersome is
having to declare it without a valid initial value, but there's
no way around that.
std::cout << "\n *** Printing WOrds ***\n";
for(unsigned int i=0; i < collect_input.s ize(); ++i)
std::cout << collect_input[i]
<< '\n';
Use std::size_t instead of unsigned int when you iterate on a vector. In
the std::cout line, I'd have put all the code in one line, since there
is no readability issue in separating it.
In this case, no. If you do have to break it into separate
lines, I'd align the << characters, to facilitate reading.

Also, I'd generally go for std::endl instead of '\n', especially
in beginner's code.

And of course, you just aren't "in" unless you use iterators
instead of indexes:-).
Also, pay attention with the
for without parenthesis,
You mean braces, I think. ("{}", and not "()".)
there is nothing bad with them, but it has to
be very obvious that there is only an instruction behind them.
Otherwise, they can generate errors quite hard to detect.
I think it's largely a question of conventions. If the opening
brace is on the same line as the for/if/while (as he's doing),
it's generally a good idea to systematically use braces, since
the opening brace (or its absense) is easily overlooked. If the
opening brace is on a separate line, I have no real problem with
dropping the braces.

The important thing is to chose one style, and use it
consistently.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 10 '07 #25
On Apr 10, 12:12 pm, "Duane Hebert" <s...@flarn2.co mwrote:
I would tend to use the more narrow scope and later
construction unless profiling showed it to be a bottleneck.
I've never had this be the case though.
And measure after as well. The one time I actually measured, it
turned out that the narrower scope was faster---in the case in
question, that the copy constructor was faster than the
assignment operator.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Apr 10 '07 #26
On Apr 9, 1:38 pm, "Daniel T." <danie...@earth link.netwrote:
"arnuld" <geek.arn...@gm ail.comwrote:
for(unsigned int i=0; i < collect_input.s ize(); ++i)
std::cout << collect_input[i]
<< '\n';
A more idiomatic way of doing the above is to use std::copy:
std::copy( collect_input.b egin(), collect_input.e nd(),
ostream_iterato r<std::string> ( cout, "\n" ) );
There's such a thing as a bad idiom. The ostream_iterato r will
actually work here, but it doesn't in general; it doesn't give
enough control over the output format. (In general, it doesn't
allow using a separator, rather than a terminator. And try to
use it to get a right-aligned column of int's.) It's of little
enough use that I would not recommend wasting the time to learn
it.
return 0;
}
One last thing, I think you will find that the above program will print
words twice if they are entered twice. Look up std::set.
It will also return 0 even if there is an error. Not a big deal
for a learning program, but it's never to late to develop good
habits:

std::cout.flush () ;
return std::cout ? EXIT_SUCCESS : EXIT_FAILURE ;

(In production code, of course, one would want an error message,
and not just a change in the return code.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 10 '07 #27
On Apr 10, 6:11 am, "arnuld" <geek.arn...@gm ail.comwrote:
On Apr 10, 1:56 am, "Daniel T." <danie...@earth link.netwrote:
[...]
The hardest part of this exorcise is to remove duplicates *without*
sorting the input.
(I'm sure he meant "exercise", but it's an interesting slip.)
that is what "std::set" does.
No it's not. "std::set" keeps things sorted.

I think his point about the hard part is that it requires some
additional checking. Something like:

while ( std::cin >word && word != "quit" ) {
if ( /* word not yet seen */ ) {
collector.push_ back( word ) ;
}
}

There are several way of implementing the part in comments: the
simplest is probably to use std::find on the vector, but that
becomes slow when the number of words becomes large.
Alternatively, you keep the words in both a set and a vector,
and only insert when you don't find it in the vector.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 10 '07 #28

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
3142
by: Oplec | last post by:
Hi, I am learning standard C++ as a hobby. The C++ Programming Language : Special Edition has been the principal source for my information. I read the entirety of the book and concluded that I had done myself a disservice by having not attempted and completed the exercises. I intend to rectify that. My current routine is to read a chapter and then attempt every exercise problem, and I find that this process is leading to a greater...
7
2345
by: arnuld | last post by:
problem: define functions F(char), g(char&) & h(const char&). call them with arguments 'a', 49, 3300, c, uc & sc where c is a char, uc is unsigned char & sc is signed char. whihc calls are legal? which calls cause the compiler to to introduce a temporary variable? solution: this is the code ----------------------------------------------------------- #include <iostream> void f(char) {};
0
1747
by: arnuld | last post by:
Stroustrup has a table in section 4.9 of declarations and definitions. he asks to write a similar table but in opposite sense: char ch; // declaration with definition he asks to do the opposite as an exercise which is writing it as a "declaration without definition". please check whether i am right or wrong:
0
1751
by: arnuld | last post by:
this programme runs without any trouble. it took 45 minutes of typing. i posted it here so that people can save their precious time: // Stroustrup special edition // chapter 4 exercise 2 // printing the sizes of different types
2
5332
by: arnuld | last post by:
MAX and MIN values of CHAR could not be displayed. Why ? BTW, any advice on improvement ? (please remember i have covered chapter 4 only) ------------- PROGRAMME -------------- /* Stroustrup 3e, section 4.11, exercise 5 STATEMENT:
16
2368
by: arnuld | last post by:
i did what i could do at Best to solve this exercise and this i what i have come up with: ----------- PROGRAMME -------------- /* Stroustrup 5.9, exercise 3 STATEMENT: Use typedef to define the types: unsigned char
11
1834
by: arnuld | last post by:
/* Stroustrup: 5.9 exercise 7 STATEMENTS: Define a table of the name sof months o fyear and the number of days in each month. write out that table. Do this twice: 1.) using ar array of char for names of months and an array of numbers for number of days. 2.) using an array of structures. each structure holds the name of the
6
3037
by: arnuld | last post by:
this one was much easier and works fine. as usual, i put code here for any further comments/views/advice: --------- PROGRAMME ------------ /* Stroustrup: 5.9 exercise 7 STATEMENTS: Define a table of the name sof months o fyear and the number of days in each month. write out that table. Do this twice:
14
2470
by: arnuld | last post by:
there is no "compile-time error". after i enter input and hit ENTER i get a run-time error. here is the code: ---------- PROGRAMME -------------- /* Stroustrup, 5.9, exercise 11 STATEMENT: Read a sequence of words from the input. use "quit" as the word
0
8676
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9029
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8897
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8867
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7732
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6522
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2332
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.