开发者

C++ vector of strings, pointers to functions, and the resulting frustration

开发者 https://www.devze.com 2022-12-29 16:28 出处:网络
So I am a first year computer science student, for on of my final projects, I need to write aprogram that takes a vector of strings, and applies various functions to these. Unfortunately, I am really

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>
#inc开发者_开发技巧lude <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;
    }
 }


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) { /* ... */ }


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)".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号