On Mon, 5 Apr 2004 23:07:44 +0200, "Huibuh" <no.spam@t-online.de> wrote:
[color=blue]
>The following code is a function called from the main. Sence is to
>initialize a vector of the dimension of "a". "b" is the according value (all
>the same in a vector).
>
>The problem is that the initialization is done the right way (controled by
>the output) but the returned vector is empty - meaning the pointer is
>showing zero.
>
>
>
>vector<int>* initialize (int a, vector<int>* vec, int b)
>
>{
>
> vector<int> ve;
>
>
>
> vec=&ve;
>
> ve.reserve(a);
>
> for (int i=0; i<=a-1; i++)
>
> ve[i]=b;
>
> for (i=0; i<=a-1; i++)
>
> cout << i << ". value : "
>
> << ve[i] << endl;
>
> return vec;
>
> ve.clear();
>
>}
>
>
>
>
>
>What is wrong???[/color]
You're creating an entire local vector in your function, setting it up, and
then it gets destroyed upon exit from the function. How about just
dispensing with the local vector and using the pointer your function is
given:
#include <iostream>
#include <vector>
using namespace std;
vector<int>* initialize (int a, vector<int>* vec, int b)
{
//vector<int> ve;
// vec=&ve;
vec->reserve(a);
for (int i=0; i<=a-1; i++)
(*vec)[i]=b;
for (i=0; i<=a-1; i++)
cout << i << ". value : "
<< (*vec)[i] << endl;
return vec;
}
int main()
{
vector<int> x;
vector<int> *vecp = initialize(10, &x, 1000);
cout << x[0] << " " << x[1] << " " << x[2] << endl;
return 0;
}
[color=blue]
>
>I have tried it before without using a pointer - same result![/color]
Not sure what you mean, but not sure it matters. You /could/ have the
vector be returned by value, but that would be rather inefficient.
-leor
[color=blue]
>[/color]
--
Leor Zolman --- BD Software ---
www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: Download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html