how to pass vectors

lets say i have a function that calls a function that fills a vector (declared in the header file) like this:
1
2
3
4
5
6
7
8
9
10
void
class::foo()
{
bar( pointer)
}
void
class::bar( pointer )
{
int vec(array, array + sizeof array / sizeof array[0]) ; 
}


and i want to use that vector in many other functions in the class like this:
1
2
3
4
5
string 
class::foobar_str() const
{
need to read vector here and return const string
}

i tried a few things but nothing worked. Any help will be greatly appreciated. Thanks.



> i tried a few things but nothing worked
maybe you should try to write in c++

I don't understand your description, and your code makes no sense.

1
2
3
4
5
6
7
8
9
10
11
12
class foo{
   std::vector<int> v;
public:
   void fill(){
      int n;
      while(std::cin>>n)
         v.push_back(n);
   }
   std::string bar() const{
      return v.empty()? "hello": "world";
   }
};
obviously its not real code. its meant to describe what i am trying to do. let me ask this? if i a fill a vector in one function, and that vector is declared in the header file, will that filled vector be able to be read by other member functions? i don't want to have to return it, or pass it in parameter. i want to set it once, the computation is to expensive to keep doing and returning.
¿how is the vector declared?
If it is a member variable, all member functions may access it
If it is a static member variable, all member functions from all the objects of that class may access it
If it is global, all can access it.
A vector is just an object like any other. Its persistence will depend on how you declare it, just as ne555 says, just like any other object.
hey thanks. the vector is declared in the private section of the header file.
1
2
3
4
5
6
7
8
9
10
11
class child : public parent
{
public:
   //functions declared here
protected:
  //functions declared here
private:
  //functions declared here

  //vector declared here
}


so once the vector is filled, all the other functions can read the contents of that vector?
Last edited on
The vector will keep its state for the lifetime of the object of which it is a member. Just like any other data member.
Thanks. And because it is declared in the header, it is available to every other function without being passed as parameter or returned???
It's declared as a private member - as is usually correct for class data members - so it is visible only to other methods of the class.

If any code outside the class needs to access the contents of the vector, you'll need to pass it via a public method. When doing so, you'll need to consider whether you're passing a copy of the vector, or a reference/pointer to the actual data member, considering issues such as separation of interface and implementation, ownership of data, and the lifetime of the class and the validity of those pointers/references.
Thanks!
You're welcome :)
Topic archived. No new replies allowed.