[英]C++ vector of strings, pointers to functions, and the resulting frustration
So I am a first year computer science student, for on of my final projects, I need to write a program that takes a vector of strings, and applies various functions to these. 因此,我是计算机科学专业的一年级学生,因为在我的最后一个项目中,我需要编写一个程序,该程序采用字符串向量,并对这些字符串应用各种功能。 Unfortunately, I am really confused on how to use pointer to pass the vector from function to function. 不幸的是,我对如何使用指针将向量从一个函数传递到另一个函数感到非常困惑。 Below is some sample code to give an idea of what I am talking about. 以下是一些示例代码,可以让我大致了解一下。 I also get an error message when I try to deference any pointer. 当我尝试引用任何指针时,我还会收到一条错误消息。
thanks. 谢谢。
#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
is not std::vector<T>*
, it is T*
. std::vector<T>::pointer
不是std::vector<T>*
,它是T*
。
Don't worry about using pointers; 不用担心使用指针。 just use references, eg, 只需使用引用,例如
void function_1(std::vector<string>& vec) { /* ... */ }
function_2
, which does not modify the vector, should take a const reference: 不修改向量的function_2
应该采用const引用:
void function_2(const std::vector<string>& vec) { /* ... */ }
Make "vector::pointer" = "vector*" 使“ vector :: pointer” =“ vector *”
Also note that there are other issues, not having to do with your question, such as "*ptr.pushback(line)" actually meaning something completely different from what you think. 另请注意,还有其他问题,与您的问题无关,例如“ * ptr.pushback(line)”实际上意味着与您的想法完全不同的事物。 That should be "ptr->pushback(line)". 那应该是“ ptr-> pushback(line)”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.