views:

171

answers:

2

So I am a first year computer science student, for on of my final projects, I need to write a program that takes a vector of strings, and applies various functions to these. Unfortunately, I am really confused on how to use pointer to pass the vector from function to function. Below is some sample code to give an idea of what I am talking about. I also get an error message when I try to deference any pointer.

thanks.

#include <iostream>
#include <cstdlib>
#include <vector>
#include <string>

using namespace std;

vector<string>::pointer function_1(vector<string>::pointer ptr);
void function_2(vector<string>::pointer ptr);


int main()
{
   vector<string>::pointer ptr;
   vector<string> svector;

   ptr = &svector[0];

   function_1(ptr);
   function_2(ptr);
}

vector<string>::pointer function_1(vector<string>::pointer ptr)
{
   string line;

   for(int i = 0; i < 10; i++)
   {
       cout << "enter some input ! \n"; // i need to be able to pass a reference of the vector
       getline(cin, line);              // through various functions, and have the results 
      *ptr.pushback(line);             // reflectedin main(). But I cannot use member functions  
   }                                      // of vector with a deferenced pointer.

   return(ptr);
 }

 void function_2(vector<string>::pointer ptr)
 {
    for(int i = 0; i < 10; i++)
    {
       cout << *ptr[i] << endl;
    }
 }
+10  A: 

std::vector<T>::pointer is not std::vector<T>*, it is T*.

Don't worry about using pointers; just use references, e.g.,

void function_1(std::vector<string>& vec) { /* ... */ }

function_2, which does not modify the vector, should take a const reference:

void function_2(const std::vector<string>& vec) { /* ... */ }
James McNellis
DeadMG
This is the right answer. Don’t use pointers unless it’s not possible to use references.
Nate
I'm going to try this one, Thanks!
Kyle
A: 

Make "vector::pointer" = "vector*"

Also note that there are other issues, not having to do with your question, such as "*ptr.pushback(line)" actually meaning something completely different from what you think. That should be "ptr->pushback(line)".

Noah Roberts
not counting the fact that pushback doesn't exist and that it's actually push_back. But like James said using references will make your headaches go away.
jonathanasdf
yeah, sorry I didn't check over it before I posted.
Kyle