所以我是计算机科学专业的一年级学生,在我的期末项目中,我需要编写一个程序来获取字符串 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/