【发布时间】:2018-12-13 10:48:46
【问题描述】:
您好,我正在尝试理解算法,但我只是不明白在函数中使用它们。在这种情况下,将向量传递给函数。理解的主要问题是“string* ptrToElement(vector<string>* const pVec, int i)"的返回部分。我不知道为什么在这个函数中返回时,"return (&( (*pVec)[i] ))",为什么pvec有一个*。为什么它是一个指针。这让我感到困惑理解,我不明白为什么 pvec 有
string* ptrToElement(vector<string>* const pVec, int i);
int main()
{
vector<string> vecInventory;
vecInventory.push_back("sword");
vecInventory.push_back("shield");
vecInventory.push_back("armour");
cout << "Sending the object pointed to by returned pointer: " << endl;
cout << *( ptrToElement(&vecInventory,0) ) << endl << endl;
int iTemp = 0;
cin >> iTemp;
return (0);
}
string* ptrToElement(vector<string>* const pVec, int i)
{
return (&( (*pVec)[i] ));
}
【问题讨论】:
-
pVec不必是指针。一个更合理的函数应该是这样的:string& refToElement(vector<string>& vec, int i) { return vec[i]; }虽然目前还不清楚为什么需要一个辅助函数,而不是在必要时写vec[i]。 -
这实际上是给出的练习表的一部分。我试图理解其中的每一件事。唯一让我难过的是 pvec 是函数返回中的指针。我知道执行这个小练习的主要目的的其他方法。但是是的...
标签: c++ algorithm vector parameter-passing