字符串的C ++向量,函数指针以及由此产生的挫败感

时间:2010-05-10 23:09:23

标签: c++ pointers

所以我是第一年的计算机科学专业的学生,​​在我的最终项目中,我需要编写一个带有字符串向量的程序,并将各种函数应用于这些。不幸的是,我真的很困惑如何使用指针将向量从函数传递给函数。下面是一些示例代码,以便了解我在说什么。当我尝试使用任何指针时,我也会收到错误消息。

感谢。

#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;
    }
 }

2 个答案:

答案 0 :(得分:10)

std::vector<T>::pointer不是std::vector<T>*,而是T*

不要担心使用指针;只需使用引用,例如,

void function_1(std::vector<string>& vec) { /* ... */ }
不修改向量的

function_2应该采用const引用:

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

答案 1 :(得分:0)

制作“vector :: pointer”=“vector *”

另请注意,还有其他问题,与您的问题无关,例如“* ptr.pushback(line)”实际上意味着与您的想法完全不同的东西。那应该是“ptr-&gt; pushback(line)”。

相关问题