| re: Refs. in std::vector, ctor arguments, etc
Jim Langston skrev:[color=blue]
> "Pelle Beckman" <hejpelle@chello.se> wrote in message
> news:z8kxe.40$qE5.39@amstwist00...
>[color=green]
>>Hi all,
>>
>>I have a few - beginners - questions:
>>
>>* Why can't I put object references in a std::vector,
>> i.e std::vector<MyClass&> ?
>> At least in doesnt work in gcc (mingw, win32)[/color]
>
>
> I don't know. Just store the pointer. std::vector<MyClass*>[/color]
Well, I'd like to but I want to be able
to delete the objects in the vector later
and references seem nicer.
Besides, I suck at C++ pointer syntax.
[color=blue]
>[color=green]
>>* What's the difference between passing
>> member inits in the c-tor funtion from
>> doing them as "ordinary" vars?
>>
>> i.e
>> MyClass::MyClass : my_member1 (5), my_member (2) { }
>> as opposed to
>> MyClass::MyClass { my_member1 = 5; my_member = 2; }[/color]
>
>
> Some things can only be initialized in the ctor initialization list.
> Constant values being one of them. Other classes being another.
>
> I.E.
>
> class MyClass
> {
> const int MyInt;
> SomeClass MyObject; <-- No default ctor
> MyClass():MyInt(10), MyObject(20) {}; <-- Works
> MyClass() { MyInt = 10; }; <-- Doesnt' work (Can't even figure
> . how you'd try to
> initialize MyObject
> }
>
> I've also been told that it is 3x's faster to initialize them in the
> initializer list. Not sure if this is true or not.
>
>[color=green]
>>* I'm looping through a std::vector using iterators.
>> Under some criterias I want to access certain elements
>> of that vector using the following code:
>>
>> std::vector<MyClass>::iterator it = MyVector.begin();
>> int i = 0;
>> while (it != MyVector.end()) {
>>if (some_condition) {
>>MyVector.at(i) = some_value;
>>}
>> i++;
>> it++;
>> }
>>
>> Isn't there some way to do this without
>> using the somewhat ugly "i" value? Is there some
>> way of using the iterator as a vector element "indexer"?[/color]
>
>
> Yes. *it would refer to the object instance.
>
> std::vector<MyClass>::iterator it;
> for ( it = MyVector.begin(); it != MyVector.end(); ++it )
> {
> if ( some_condition )
> {
> *it = some_value; //or
> *it.ObjectMethod(10)
> }
> }
>
>[/color]
Thanks for you answers! |