473,698 Members | 2,609 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 2441
Anand Hariharan wrote:
On Apr 9, 5:34 am, Zeppe <z...@email.itw rote:
>>
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.

What does "declaring variables close to first use" have to do with
performance?
It is a common belief that for some cases (and some compilers) it is
better to declare/define an object before it's going to be used, and
especially if the use is in the loop. IOW, it's better to write

SomeType object;
while (blah) {
object = someexpression; // assignment
somehow_use_tha t(object); // use
}

than

while (blah) {
SomeType object = someexpression; // intialisation
somehow_use_tha t(object);
}

(the former case declares the variable in the scope unnecessarily
wide and sooner than the object is actually used).

It is also true that without measuring it's impossible to say for
sure.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 9 '07 #11
Victor Bazarov wrote:
Anand Hariharan wrote:
>>On Apr 9, 5:34 am, Zeppe <z...@email.itw rote:
>>>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.

What does "declaring variables close to first use" have to do with
performance ?


It is a common belief that for some cases (and some compilers) it is
better to declare/define an object before it's going to be used, and
especially if the use is in the loop. IOW, it's better to write

SomeType object;
while (blah) {
object = someexpression; // assignment
somehow_use_tha t(object); // use
}

than

while (blah) {
SomeType object = someexpression; // intialisation
somehow_use_tha t(object);
}

(the former case declares the variable in the scope unnecessarily
wide and sooner than the object is actually used).
This appears to contradict your first paragraph.

--
Ian Collins.
Apr 9 '07 #12
Ian Collins wrote:
Victor Bazarov wrote:
>Anand Hariharan wrote:
>>On Apr 9, 5:34 am, Zeppe <z...@email.itw rote:

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.

What does "declaring variables close to first use" have to do with
performance ?


It is a common belief that for some cases (and some compilers) it is
better to declare/define an object before it's going to be used, and
especially if the use is in the loop. IOW, it's better to write

SomeType object;
while (blah) {
object = someexpression; // assignment
somehow_use_tha t(object); // use
}

than

while (blah) {
SomeType object = someexpression; // intialisation
somehow_use_tha t(object);
}

(the former case declares the variable in the scope unnecessarily
wide and sooner than the object is actually used).
This appears to contradict your first paragraph.
Contradict? How? The belief is that the former (declaring outside
the 'while' loop) is better. I am not claiming any side in that
belief. I am not saying "contrary to the belief it's better to do
it that way" (in case you are reading it that way).

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 9 '07 #13
Victor Bazarov wrote:
Ian Collins wrote:
>>Victor Bazarov wrote:
>>>Anand Hariharan wrote:

On Apr 9, 5:34 am, Zeppe <z...@email.itw rote:

>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.

What does "declaring variables close to first use" have to do with
performance ?

It is a common belief that for some cases (and some compilers) it is
better to declare/define an object before it's going to be used, and
especially if the use is in the loop. IOW, it's better to write

SomeType object;
while (blah) {
object = someexpression; // assignment
somehow_use_tha t(object); // use
}

than

while (blah) {
SomeType object = someexpression; // intialisation
somehow_use_tha t(object);
}

(the former case declares the variable in the scope unnecessarily
wide and sooner than the object is actually used).
This appears to contradict your first paragraph.

Contradict? How? The belief is that the former (declaring outside
the 'while' loop) is better. I am not claiming any side in that
belief. I am not saying "contrary to the belief it's better to do
it that way" (in case you are reading it that way).
OK, I thought you were expressing a preference for the first form and
then criticising it at the end. I realy should stop interpreting IOW as
Isle Of Wight!

--
Ian Collins.
Apr 9 '07 #14

"Victor Bazarov" <v.********@com Acast.netwrote in message
news:ev******** **@news.datemas .de...
>>(the former case declares the variable in the scope unnecessarily
wide and sooner than the object is actually used).
This appears to contradict your first paragraph.

Contradict? How? The belief is that the former (declaring outside
the 'while' loop) is better. I am not claiming any side in that
belief. I am not saying "contrary to the belief it's better to do
it that way" (in case you are reading it that way).
I think the words "unnecessar ily" and "sooner than" tend
to show a bias.
Apr 9 '07 #15
TB
arnuld skrev:
>On Apr 9, 2:07 pm, "arnuld" <geek.arn...@gm ail.comwrote:

i just did not get 2 things:

> // sorting the input
sort(collect_in put.begin(), collect_input.e nd());

why "std::sort" does not work ?? (as "algorithm" is a standard
library)

>-------- OUTPUT ----------
[arch@voodo tc++pl]$ g++ -ansi -pedantic -Wall -Wextra -O
ex_5.9-11.cpp
[arch@voodo tc++pl]$ ./a.out
like this and wahout
Quit quiT and quit

*** Printing Sorted Words ***
Quit
and
and
like
quiT
this
wahout
[arch@voodo tc++pl]$

why "Quit" came before "and" ?
Because 'Q' = 81 and 'a' = 97 according
to unicode and ascii.

--
TB
Apr 9 '07 #16
Duane Hebert wrote:
"Victor Bazarov" <v.********@com Acast.netwrote in message
news:ev******** **@news.datemas .de...
>>>(the former case declares the variable in the scope unnecessarily
wide and sooner than the object is actually used).

This appears to contradict your first paragraph.

Contradict? How? The belief is that the former (declaring outside
the 'while' loop) is better. I am not claiming any side in that
belief. I am not saying "contrary to the belief it's better to do
it that way" (in case you are reading it that way).

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?

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.

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.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Apr 10 '07 #17
On Apr 10, 1:56 am, "Daniel T." <danie...@earth link.netwrote:
"arnuld" <geek.arn...@gm ail.comwrote:
1.) why do i need to "copy" the whole vector ?

You have to copy the whole vector to cout. That is what you are doing
when you print all the strings.
OK, it means , "std::cout" always copies its input.

2.) is "std::cout" is less maintainable/readable than
"ostream_iterat or" ?
No, but the loop itself is.
for ( std::vector<std ::string>::iter ator i = collected_input .begin();
i != collected_input .end(); ++i )
{
cout << *i << '\n';

}
The above works, but if you decide to change the container to anything
other than a vector, you have to change the loop also.

for ( unsigned i = 0; i < collected_input .size(); ++i )
{
cout << collected_input[i] << '\n';

}
The above also works but only for vectors and deques, not for lists or
sets.
i tried std::set, it does not make any sense to me, as of now. it is
on page 491, section 17.4.3 of Stroustrup (special edition).
With std::set, you insert the item instead of using push_back and it
keeps the items sorted.
What you came up with is great for satisfying the last sentence of the
requirement, but not the first 3.
i got it, you mean it is not a good programme at all. i need to
rewrite.
The hardest part of this exorcise is to remove duplicates *without*
sorting the input.
that is what "std::set" does. here is my try with a compile-time error
i am unable to figure out why. i tried eve "std::ostream_i terator" but
same error:

-------- PROGRAMME --------

#include<iostre am>
#include<string >
#include<algori thm>
#include<set>
#include<iterat or>

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_iterato r<std::string>( std::cout, '\n');

return 0;
}

----- OUTPUT ---------
[arch@voodo tc++pl]$ g++ -ansi -pedantic -Wall -Wextra -O
ex_5.9-11_modified.cpp
ex_5.9-11_modified.cpp : In function 'int main()':
ex_5.9-11_modified.cpp :30: error: 'ostream_iterat or' was not declared
in this scope
ex_5.9-11_modified.cpp :30: error: expected primary-expression before
'>' token
ex_5.9-11_modified.cpp :30: warning: left-hand operand of comma has no
effect
[arch@voodo tc++pl]$

Apr 10 '07 #18
arnuld wrote:
>
that is what "std::set" does. here is my try with a compile-time error
i am unable to figure out why. i tried eve "std::ostream_i terator" but
same error:

-------- PROGRAMME --------

#include<iostre am>
#include <ostream>
#include<string >
#include<algori thm>
#include<set>
#include<iterat or>

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_iterato r<std::string>( std::cout, '\n');

return 0;
}

----- OUTPUT ---------
[arch@voodo tc++pl]$ g++ -ansi -pedantic -Wall -Wextra -O
ex_5.9-11_modified.cpp
ex_5.9-11_modified.cpp : In function 'int main()':
ex_5.9-11_modified.cpp :30: error: 'ostream_iterat or' was not declared
in this scope
ex_5.9-11_modified.cpp :30: error: expected primary-expression before
'>' token
ex_5.9-11_modified.cpp :30: warning: left-hand operand of comma has no
effect
[arch@voodo tc++pl]$
Apr 10 '07 #19
Ignore my previous post. You forgot std:: on ostream_iterato r. Also,
missing a close paren on std::copy. See embedded.

arnuld wrote:
>
-------- PROGRAMME --------

#include<iostre am>
#include<string >
#include<algori thm>
#include<set>
#include<iterat or>

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_iterato r<std::string>( std::cout, '\n');
std::ostream_it erator<std::str ing(std::cout, '\n'));
>
return 0;
}
Apr 10 '07 #20

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
8608
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8898
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
8870
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
7734
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...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4370
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3051
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
3
2006
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.