[英]C++ vector of strings, pointers to functions, and the resulting frustration
因此,我是计算机科学专业的一年级学生,因为在我的最后一个项目中,我需要编写一个程序,该程序采用字符串向量,并对这些字符串应用各种功能。 不幸的是,我对如何使用指针将向量从一个函数传递到另一个函数感到非常困惑。 以下是一些示例代码,可以让我大致了解一下。 当我尝试引用任何指针时,我还会收到一条错误消息。
谢谢。
#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
应该采用const引用:
void function_2(const std::vector<string>& vec) { /* ... */ }
使“ vector :: pointer” =“ vector *”
另请注意,还有其他问题,与您的问题无关,例如“ * ptr.pushback(line)”实际上意味着与您的想法完全不同的事物。 那应该是“ ptr-> pushback(line)”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.