Re: A problem about "vector" for c++ beginner

From: Jerry Coffin (jcoffin_at_taeus.com)
Date: 10/13/04


Date: 13 Oct 2004 09:46:49 -0700


"Larky Mi" <LarkyMi@discussions.squaresoft.com> wrote in message news:<ha6pm0dj43vdeskdpc6epa78k7cq8djes9@news.yaako.com>...

[ ... ]

> void print_vector(vector<int> ivec)
> {
> if (ivec.empty())
> return;
>
> for(int ix=0;ix<ivec.size();++ix)
> cout<<ivec[ix]<<' ';

[ ... ]

> Warning W8012 F:\Borland\BCC55\Project\example_p100.cpp 11: Comparing signed > and
> unsigned values in function print_vector(std::vector<int,std::allocator<int>
>)

Basically, it's trying to tell you that vector::size() returns an
unsigned integer, and ix is a signed int. Mixing the two (such as
'ix<ivec.size()') can give rather strange results -- in theory, the
number of elements in a vector could be outside the range than int can
represent, in which case your code almost certainly won't work
correctly.

The obvious cure for this is to change ix to an unsigned int. The less
obvious but theoretically better way would use std::vector::size_type.
I, however, would advise against either one, and instead eliminate the
problem of picking the type, by eliminating the type, the variable,
and indeed the whole loop, instead using something like this:

std::copy(ivec.begin(), ivec.end(),
    std::ostream_iterator<int>(std::cout, " "));

-- 
    Later,
    Jerry.
The universe is a figment of its own imagination.


Relevant Pages

  • Re: Better use of random number genator bits?
    ... This on average is a total of about 2880 bits to shuffle a deck (of course ... Let's choose a random 32-bit unsigned integer and check if it is ... int i, j, n; ... randnum_UL = KISS; ...
    (sci.math)
  • Re: data types
    ... sizeof tells me there are 4 bytes to an int. ... Depending on what you are doing, you might want to consider as an alternative what is generally used where I used to work and generally called with "wrap angles" or BAMs. ... Unsigned integer types are guaranteed by the C standard to wrap. ... There are also various IDEs using gcc. ...
    (comp.lang.c)
  • Re: Comparing with 0.
    ... Not "unsigned", but signed int:) ... Arithmetic AND the unsigned integer with the ... Test for zero. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: 2.3 -> 2.4: long int too large to convert to int
    ... long int too large to convert to int ... How do I tell Python that 0xc0047a80 is an ... somehow cobble together some way of forcing an unsigned integer into a ... signed integer. ...
    (comp.lang.python)
  • Re: questions about size_t
    ... size_t is an unsigned integer type large enough to hold the value returned from sizeof. ... The actual int types that correspond to size_t can vary. ... Should I change that to size_t if I need to compare the i ...
    (comp.lang.c)