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

标签 c++ pointers

所以我是计算机科学专业的一年级学生,在我的期末项目中,我需要编写一个程序来获取字符串 vector ,并对这些 vector 应用各种函数。不幸的是,我真的很困惑如何使用指针将 vector 从一个函数传递到另一个函数。下面是一些示例代码,可以让您了解我在说什么。当我尝试引用任何指针时,我也会收到一条错误消息。

谢谢。

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

最佳答案

std::vector<T>::pointer不是 std::vector<T>* , 它是 T* .

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

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

function_2 ,它不修改 vector ,应该采用常量引用:

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

关于字符串的 C++ vector 、指向函数的指针以及由此产生的挫败感,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2807048/

相关文章:

C - 将新数据附加到链表也会更改以前的数据

c++ - 写入和读取图像 OpenGL 的内存屏障问题

c++ - 如何在 linux 上编译 C++ 以制作 windows 二进制文件

C - 如何找到结构的大小?

c++ - 向后移动下一个节点函数

c++ - 确保 `std::vector` 不会移动其指针

c++ - 使用类型的参数包和相应值的输入数组构造类型

c++ - 为什么不调用复制构造函数?

c++ - 函数返回数组中最大元素的地址

剪掉一段字符串