473,782 Members | 2,439 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

playing with vectors

/* C++ Primer 4/e

* STATEMENT
* given 2 vectors of integers, write a programme to determine
whether one vector * is the prefix of the other vector e.g. if 1st vector
has elements (0,1,1,2) and 2nd * vecotr has elements (0,1,1,2,3,5,8) then
programme should say "TRUE" and if 2nd * vector is smaller then too it
should say "TRUE", else it should say "FALSE". *
*/
#include<iostre am>
#include<vector >

int main()
{
std::vector<int ivec1, ivec2;
int ival;

/* creation of 1st vector */
std::cout << "Enter elements for 1st vector" << std::endl;
while(std::cin >ival)
{
ivec1.push_back (ival);
}

std::cout << "1st vector is created with elements: ";
for(std::vector <int>::const_it erator iter=ivec1.begi n();
iter != ivec1.end(); ++iter)
{
std::cout << *iter << " ";
}

std::cout << "\n-------------------" << std::endl;

/* creation od 2nd vector */
ival = 1; /* because ival had EOF value since used last time */
std::cout << "Now enter elements for 2nd vector" << std::endl;
while(std::cin >ival)
{
ivec2.push_back (ival);
}
std::cout << "2st vector is created with elements: ";
for(std::vector <int>::const_it erator iter=ivec2.begi n();
iter != ivec2.end(); ++iter)
{
std::cout << *iter << " ";
}

std::cout << std::endl << std::endl;

unsigned sizeSmaller;
int size1 = ivec1.size();
int size2 = ivec2.size();

/* this "if-else" clause will make the next "for" loop a generalise one
and the "else clause" will work even for vectors of same length */
if(size1 < size2)
{
sizeSmaller = size1;
}
else
{
sizeSmaller = size2;
}

bool prefix_test = true;
for(std::vector <int>::size_typ e ix=0;
(ix != sizeSmaller) && prefix_test;
++ix)
/* notice the test-condition:
1st, "ix" is an unsigned int and that is why we made sizeSmaller an
unsigned int. 2nd condition will break the loop as soon as we will
meet with 1st false test :) */
{
if(ivec1[ix] != ivec2[ix])
{
prefix_test = false;
}
}
/* print the result */
if(prefix_test)
{
std::cout << "--TRUE" << std::endl;
}
else
{
std::cout << "--FALSE" << std::endl;
}

return 0;
}
this programme compiles and runs but it has a semantic bug. i intended
that it will ask me to input elements for both vectors but it only askes
me to input elements for the 1st vector. it seems like the 2nd while loop
never runs. here is the ouput:

[arnuld@arch cpp] $ g++ -ansi -pedantic -Wall -Wextra ex_06-15.cpp
[arnuld@arch cpp] $ ./a.out
Enter elements for 1st vector
1
2
3
1st vector is created with elements: 1 2 3 -------------------
Now enter elements for 2nd vector
2st vector is created with elements:

--TRUE
[arnuld@arch cpp] $
--
http://arnuld.blogspot.com

Aug 3 '07 #1
5 1617
arnuld wrote:
/* C++ Primer 4/e
[..]
}
this programme compiles and runs but it has a semantic bug. i intended
that it will ask me to input elements for both vectors but it only
askes me to input elements for the 1st vector. it seems like the 2nd
while loop never runs.
Well, how do you end the input of the first vector? Apparently you
tell the system your standard input has no more data, right? Did you
press Ctrl-D? If so, how do you expect to read the elements of the
second vector from the same input [that has no more data]?

Think about a different way of terminating the input of the first
vector.
here is the ouput:
The *output* is irrelevant. The *input* is what's screwing you up.
>
[arnuld@arch cpp] $ g++ -ansi -pedantic -Wall -Wextra ex_06-15.cpp
[arnuld@arch cpp] $ ./a.out
Enter elements for 1st vector
1
2
3
1st vector is created with elements: 1 2 3 -------------------
Now enter elements for 2nd vector
2st vector is created with elements:

--TRUE
[arnuld@arch cpp] $
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 3 '07 #2
On 2007-08-03 13:57, arnuld wrote:
/* C++ Primer 4/e

* STATEMENT
* given 2 vectors of integers, write a programme to determine
whether one vector * is the prefix of the other vector e.g. if 1st vector
has elements (0,1,1,2) and 2nd * vecotr has elements (0,1,1,2,3,5,8) then
programme should say "TRUE" and if 2nd * vector is smaller then too it
should say "TRUE", else it should say "FALSE". *
*/
Another of the authors vague assignments, should it print TRUE if the
second vector is smaller than the first regardless of the content of the
vectors? I suspect not but its hard to tell.
>
#include<iostre am>
#include<vector >

int main()
{
std::vector<int ivec1, ivec2;
int ival;

/* creation of 1st vector */
std::cout << "Enter elements for 1st vector" << std::endl;
while(std::cin >ival)
{
ivec1.push_back (ival);
}

std::cout << "1st vector is created with elements: ";
for(std::vector <int>::const_it erator iter=ivec1.begi n();
iter != ivec1.end(); ++iter)
{
std::cout << *iter << " ";
}

std::cout << "\n-------------------" << std::endl;

/* creation od 2nd vector */
ival = 1; /* because ival had EOF value since used last time */
No need to do this, the value of ival will be overwritten when two lines
down in the loop.
std::cout << "Now enter elements for 2nd vector" << std::endl;
while(std::cin >ival)
{
ivec2.push_back (ival);
}
std::cout << "2st vector is created with elements: ";
for(std::vector <int>::const_it erator iter=ivec2.begi n();
iter != ivec2.end(); ++iter)
{
std::cout << *iter << " ";
}

std::cout << std::endl << std::endl;
Organisational tips: Create a function taking two vectors as arguments
and returns a bool which performs the check for you.
unsigned sizeSmaller;
int size1 = ivec1.size();
int size2 = ivec2.size();

/* this "if-else" clause will make the next "for" loop a generalise one
and the "else clause" will work even for vectors of same length */
if(size1 < size2)
{
sizeSmaller = size1;
}
else
{
sizeSmaller = size2;
}
Replace the above with std::min(), don't forget to include <algorithm>.
bool prefix_test = true;
for(std::vector <int>::size_typ e ix=0;
(ix != sizeSmaller) && prefix_test;
++ix)
You can get rid of prefix_test and sizeSmaller by rewriting the loop
like this:

for (std::vector<in t>::size_type ix = 0;
(ix < ivec1.size() && ix < ivec2.size());
++ix)

/* notice the test-condition:
1st, "ix" is an unsigned int and that is why we made sizeSmaller an
unsigned int. 2nd condition will break the loop as soon as we will
meet with 1st false test :) */
{
if(ivec1[ix] != ivec2[ix])
{
prefix_test = false;
}
}
/* print the result */
if(prefix_test)
{
std::cout << "--TRUE" << std::endl;
}
else
{
std::cout << "--FALSE" << std::endl;
}

return 0;
}
this programme compiles and runs but it has a semantic bug. i intended
that it will ask me to input elements for both vectors but it only askes
me to input elements for the 1st vector. it seems like the 2nd while loop
never runs.
That's because cin has reaches EOF, you need to reset it before you can
read any more, put std::cin.clear( ); before the second loop.

--
Erik Wikström
Aug 3 '07 #3

arnuld <ge*********@gm ail.comwrote in message...
>
std::cout << std::endl << std::endl;
Just a note here, that line does a 'flush' twice. It's not a bad thing, just
not good.
Try it this way:

std::cout << '\n' << std::endl; // "\n" will also work.

--
Bob R
POVrookie
Aug 3 '07 #4

"arnuld" <ge*********@gm ail.comwrote in message
news:pa******** *************** *****@gmail.com ...
/* C++ Primer 4/e

* STATEMENT
* given 2 vectors of integers, write a programme to determine
whether one vector * is the prefix of the other vector e.g. if 1st vector
has elements (0,1,1,2) and 2nd * vecotr has elements (0,1,1,2,3,5,8) then
programme should say "TRUE" and if 2nd * vector is smaller then too it
should say "TRUE", else it should say "FALSE". *
*/
#include<iostre am>
#include<vector >

int main()
{
std::vector<int ivec1, ivec2;
int ival;

/* creation of 1st vector */
std::cout << "Enter elements for 1st vector" << std::endl;
while(std::cin >ival)
{
ivec1.push_back (ival);
}
At this point std::cin is in a bad state.
std::cout << "1st vector is created with elements: ";
for(std::vector <int>::const_it erator iter=ivec1.begi n();
iter != ivec1.end(); ++iter)
{
std::cout << *iter << " ";
}

std::cout << "\n-------------------" << std::endl;

/* creation od 2nd vector */
ival = 1; /* because ival had EOF value since used last time */
std::cout << "Now enter elements for 2nd vector" << std::endl;
while(std::cin >ival)
std::cin is still in a bad state, so it won't accept any more input. You
have to reset std::cin

You should read the FAQ 15 entirely.
http://www.parashift.com/c++-faq-lit...ut.html#faq-15 or at least
until 15.6

std::cin.clear( );
std::cin.ignore (std::numeric_l imits<std::stre amsize>::max(), '\n');

should reset std::cin to a good state.

You'll want to
#include <limits>
{
ivec2.push_back (ival);
}
std::cout << "2st vector is created with elements: ";
for(std::vector <int>::const_it erator iter=ivec2.begi n();
iter != ivec2.end(); ++iter)
{
std::cout << *iter << " ";
}

std::cout << std::endl << std::endl;

unsigned sizeSmaller;
int size1 = ivec1.size();
int size2 = ivec2.size();

/* this "if-else" clause will make the next "for" loop a generalise one
and the "else clause" will work even for vectors of same length */
if(size1 < size2)
{
sizeSmaller = size1;
}
else
{
sizeSmaller = size2;
}

bool prefix_test = true;
for(std::vector <int>::size_typ e ix=0;
(ix != sizeSmaller) && prefix_test;
++ix)
/* notice the test-condition:
1st, "ix" is an unsigned int and that is why we made sizeSmaller an
unsigned int. 2nd condition will break the loop as soon as we will
meet with 1st false test :) */
{
if(ivec1[ix] != ivec2[ix])
{
prefix_test = false;
}
}
/* print the result */
if(prefix_test)
{
std::cout << "--TRUE" << std::endl;
}
else
{
std::cout << "--FALSE" << std::endl;
}

return 0;
}
this programme compiles and runs but it has a semantic bug. i intended
that it will ask me to input elements for both vectors but it only askes
me to input elements for the 1st vector. it seems like the 2nd while loop
never runs. here is the ouput:

[arnuld@arch cpp] $ g++ -ansi -pedantic -Wall -Wextra ex_06-15.cpp
[arnuld@arch cpp] $ ./a.out
Enter elements for 1st vector
1
2
3
1st vector is created with elements: 1 2 3 -------------------
Now enter elements for 2nd vector
2st vector is created with elements:

--TRUE
[arnuld@arch cpp] $
--
http://arnuld.blogspot.com

Aug 3 '07 #5
On Aug 3, 1:57 pm, arnuld <geek.arn...@gm ail.comwrote:
/* C++ Primer 4/e
* STATEMENT
* given 2 vectors of integers, write a programme to determine
whether one vector * is the prefix of the other vector e.g. if 1st vector
has elements (0,1,1,2) and 2nd * vecotr has elements (0,1,1,2,3,5,8) then
programme should say "TRUE" and if 2nd * vector is smaller then too it
should say "TRUE", else it should say "FALSE". *
*/
#include<iostre am>
#include<vector >
int main()
{
std::vector<int ivec1, ivec2;
Don't ever declare two variables in the same statement. It's
very bad practice.

More to the point, don't define variables until you need them.
In this case, you shouldn't define ivec2 until much, much later.
int ival;
/* creation of 1st vector */
std::cout << "Enter elements for 1st vector" << std::endl;
while(std::cin >ival)
{
ivec1.push_back (ival);
}
One thing: you're going to do exactly the same thing a second
time. That should have you thinking "function" immediately.
std::cout << "1st vector is created with elements: ";
for(std::vector <int>::const_it erator iter=ivec1.begi n();
iter != ivec1.end(); ++iter)
{
std::cout << *iter << " ";
}
std::cout << "\n-------------------" << std::endl;

/* creation od 2nd vector */
ival = 1; /* because ival had EOF value since used last time */
No. ival has the last successfully read value. It's std::sin
which has the EOF state. And what to do about it is far from
trivial. (Under Unix, *if* the input is from a keyboard, the
just clearing the error condition would suffice to read the
second vector. Under Unix, of course, any use will also expect
to be able to redirect the input from a file, in which case,
this suddenly won't work.)

What I'd probably do (as the simplest solution) is to read the
input line by line, stopping at either end of file OR an empty
line. (In a separate function, as I said.)
std::cout << "Now enter elements for 2nd vector" << std::endl;
while(std::cin >ival)
And this condition is guaranteed to fail immediately.
{
ivec2.push_back (ival);
}
std::cout << "2st vector is created with elements: ";
for(std::vector <int>::const_it erator iter=ivec2.begi n();
iter != ivec2.end(); ++iter)
{
std::cout << *iter << " ";
}
std::cout << std::endl << std::endl;
unsigned sizeSmaller;
int size1 = ivec1.size();
int size2 = ivec2.size();
/* this "if-else" clause will make the next "for" loop a generalise one
and the "else clause" will work even for vectors of same length */
if(size1 < size2)
{
sizeSmaller = size1;
}
else
{
sizeSmaller = size2;
}
bool prefix_test = true;
for(std::vector <int>::size_typ e ix=0;
(ix != sizeSmaller) && prefix_test;
++ix)
/* notice the test-condition:
1st, "ix" is an unsigned int and that is why we made sizeSmaller an
unsigned int. 2nd condition will break the loop as soon as we will
meet with 1st false test :) */
{
if(ivec1[ix] != ivec2[ix])
{
prefix_test = false;
}
}
The above is much more complicated than necessary. Consider
using std::vector<>:: swap() and std::equal().

On the other hand, the actual specification seems to say that if
the second vector is smaller, output the same thing as if the
first vector were a prefix of it. Strange, but perhaps
specifically part of the requirements so that you don't have to
worry about swap, etc. Just something along the lines of:

std::cout << ( ivec1.size() ivec2.size()
|| std::equal(
ivec1.begin(), ivec1.end(),
ivec2.begin() )
? "TRUE"
: "FALSE" )
<< std::endl ;
/* print the result */
if(prefix_test)
{
std::cout << "--TRUE" << std::endl;
}
else
{
std::cout << "--FALSE" << std::endl;
}

return 0;

}
this programme compiles and runs but it has a semantic bug. i
intended that it will ask me to input elements for both
vectors but it only askes me to input elements for the 1st
vector. it seems like the 2nd while loop never runs.
End of file is an "error" condition, and error conditions are
sticky in C++. One a stream encounters an error condition, that
error condition will remain until explicitly reset.

--
James Kanze (GABI Software) email:james.kan ze: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
Aug 4 '07 #6

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

Similar topics

10
15840
by: Michael Aramini | last post by:
I need to represent 1D and 2D arrays of numeric or bool types in a C++ program. The sizes of the arrays in my intended application are dynamic in the sense that they are not known at compile time, so I'd like to use an STL container class template such as valarray or vector to represent 1D arrays, and valarrays or vectors of valarrays or vectors to represent 2D arrays. As I said the sizes of the arrays in my intended application are...
5
3418
by: Pratyush | last post by:
Hi, Suppose there is a vector of objects of class A, i.e., std::vector<A> vec_A(N); The class A satisifies all the STL vector requirements. Now I wish to add some attributes for each of the objects in the vector vec_A. Suppose there are K attributes to be added. For each of the attributes I define K vectors of appropriate types. Say, the attributes have types type1, type2, ..., typeK. So I define std::vector<type1> attr1(vec_A.size());
5
2317
by: Computer Whizz | last post by:
I was reading through Accelerated C++ at work when I read through the first mention of Vectors, giving us certain functions etc. Is there any benefit of Arrays over Vectors? Since all Vectors seem to be (in my eyes at least) are glorified Arrays. - Now I know there's a bit more difference, but what exactly are the advantages of Arrays over Vectors (if any)? Oh, and please keep it in mind I am a real beginner in C++ but can
3
3246
by: Amit | last post by:
Hello. I am having some problem organizing a set of vectors. The vectors itself, could contain a pointer( say integer pointer) or could contain another object MyClass. 1>So, first of all, is there anyway where I can accomodate both the vector types into a single set. Something like a set<vector<void*>, my_compare func >. Right now, I am having them as two different set dayatypes.
4
2024
by: Dr. J.K. Becker | last post by:
Hi all, I have vectors that holds pointers to other vectors, like so: vector<whatever> x; vector<whatever*> z; z=&x; Now I add something to x
5
18240
by: madhu | last post by:
http://msdn2.microsoft.com/en-us/library/fs5a18ce(VS.80).aspx vector <intv1; v1.push_back( 10 ); //adds 10 to the tail v1.push_back( 20 ); //adds 20 to the tail cout << "The size of v1 is " << v1.size( ) << endl; v1.clear( ); //clears the vector I have a few questions:
2
8693
by: wuzertheloser | last post by:
Use the program skeleton below (starting with #include <stdio.h>) as the starting point for quiz4. Add the necessary code to the functions prob1() and prob2(), and add the other 2 functions, as described in the text below. You do not need to change anything in main(). In void prob1(void), take a double floating-point number x from the keyboard and compute the function f(x), which is defined by:
1
2066
by: Rob | last post by:
How would I do this? I want to be able to handle vectors of many different types of data and vectors that can contain any number of other vectors of data. Currently, I have a templated function that handles vectors of vectors of <typename T(which could be anything from int to vectors of something else). As well, I have specialized/overloaded functions to handle the single-level vectors of data (e.g. vector<string>). So the templated...
2
3401
by: joeme | last post by:
How would one using STL do the following tasks: 1) merge 2 sorted vectors with dupes, result shall be sorted 2) merge 2 sorted vectors without dupes, result shall be sorted 3) merge 2 unsorted vectors with dupes, result does not need to be sorted 4) merge 2 unsorted vectors without dupes, result does not need to be sorted
0
9479
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,...
0
10311
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10080
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
8967
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
6733
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
5378
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...
0
5509
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2874
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.