所以我是第一年的计算机科学专业的学生,因为在我的最终项目中,我需要编写一个带有字符串向量的程序,并将各种函数应用于这些.不幸的是,我真的很困惑如何使用指针将向量从函数传递给函数.下面是一些示例代码,以便了解我在说什么.当我尝试使用任何指针时,我也会收到错误消息.
谢谢.
#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;
}
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*lis 10
std::vector<T>::pointer不是std::vector<T>*,它是T*.
不要担心使用指针; 只是使用参考,例如,
void function_1(std::vector<string>& vec) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
function_2,不修改向量,应采用const引用:
void function_2(const std::vector<string>& vec) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1001 次 |
| 最近记录: |