Re: Strange std::vector behaviour

From: Chris (loggdogg_at_earthlink.net)
Date: 01/02/05


Date: Sun, 02 Jan 2005 07:36:13 GMT


"Cy Edmunds" <cedmunds@spamless.rochester.rr.com> wrote in message
news:YVLBd.93330$Uf.16126@twister.nyroc.rr.com...
> "Hamish" <h.dean@xtra.co.nz> wrote in message
> news:kJLBd.4441$mo2.257280@news.xtra.co.nz...
>> Hello, lately I've been having a lot of trouble with the std::vector.
>> Seems
>> to create unpredictable behaviour within my code.
>>
>> Example:
>>
>> struct Switch{
>> int i;
>> int j;
>> double d;
>> };
>>
>> std::vector<Switch> Switches;
>>
>> Now I have a for...loop:
>>
>> int h = Switches.size();
>> for(int i=0;i<Switches.size()-1;i++){
>> /*do stuff here*/
>> }
>>
>> The problem is, when h (Switches.size()) equals 0, the for...loop is
>> still
>> entered, and runs infinitely.
>>
>> However, if I use the line:
>> for(int i=0;i<h-1;i++){
>> then there is not a problem.
>>
>> Anyone got any ideas as to what is going on, cos this is ruining my New
>> Year!
>>
>
>
> std::vector<T>::size() returns an unsigned type. Hence 0 - 1 evaluates to
> something like 0xffffffff

or, you could use iterators:
typedef std::vector< Switch > tSwitchContainer
typedef tSwitchContainer::iterator tSwitchItr;

tSwitchContainer Switches;

for ( tSwitchItr cur = Switches.begin(); cur != Switches.end(); cur++)
{
    // do stuff.....
}

nice thing about this is you could use any container and the code would
still work

-c



Relevant Pages

  • Re: Strange std::vector behaviour
    ... >> struct Switch{ ... typedef std::vector< Switch> tSwitchContainer ... typedef tSwitchContainer::iterator tSwitchItr; ... tSwitchContainer Switches; ...
    (microsoft.public.vc.mfc)
  • Re: "typedef" and "enum" problem
    ... That doesn't make sense, you can't define, using a typedef, a type that can ... > I must also use typedef and enum for two data types. ... 'Colors' is meaningless. ... > switch ...
    (comp.lang.cpp)
  • C# Interop of C dll passing a struct
    ... typedef unsigned char PK_U8,*PK_PU8; 8-bit unsigned char type. ... typedef PK_WORD TSwitchIndex; Switch index type. ... typedef PK_WORD TSwitchStream, *PSwitchStream; Switch stream type. ... public static extern int CASGroupInfo(int nBoard, ref TCASGroupInfo groupInfo); ...
    (microsoft.public.dotnet.framework.interop)