【发布时间】:2013-11-23 00:15:41
【问题描述】:
本文底部的解决方案 我有这个代码:
void showMenu()
{
const vector<string> vMainOptions { "Show List",
"Enter new name" };
map<int, string> mMainOptions = vectorToMap(vMainOptions);
map<int, string>::const_iterator mIt = mMainOptions.begin();
while(mIt != mMainOptions.end())
{
cout << mIt->first << ". " << mIt->second << endl;
mIt++;
}
}
map vectorToMap(const vector<string> myVector)
{
vector<string>::const_iterator vIt = myVector.begin();
map<int, string> myMap;
while(vIt != myVector.end())
{
static int nr = 1;
myMap->insert(make_pair(nr, *vIt));
vIt++;
nr++;
}
return myMap;
}
但它给了我这些错误:
line 19: error: invalid use of template-name 'std::map' without an argument list
这是第 19 行:
map vectorToMap(const vector<string> myVector);
我尽了最大努力,尝试了很多方法来解决这个问题,但还是不行。 当所有功能都在一个函数中之前它工作得很好,但是我不能重用它所以我想为此创建一个新函数!(对不起,如果它的短文本,但我真的需要帮助)
解决方案:
void showMenu()
{
const vector<string> vMainOptions { "Show List",
"Enter new name"};
map<int, string> mMainOptions = vectorToMap(vMainOptions);
map<int, string>::const_iterator mIt = mMainOptions.begin();
while(mIt != mMainOptions.end())
{
cout << mIt->first << ". " << mIt->second << endl;
mIt++;
}
}
map<int, string> vectorToMap(const vector<string>& myVector)
{
vector<string>::const_iterator vIt = myVector.begin();
map<int, string> myMap;
while(vIt != myVector.end())
{
static int nr = 1;
myMap.insert(make_pair(nr, *vIt));
vIt++;
nr++;
}
return myMap;
}
【问题讨论】:
-
您将映射分配给 void 类型函数 (vectorToMap)。 mMainOptions 不能分配给 void 类型。而且 vectorToMap 不返回任何东西。在完全声明之前,您还在 vectorToMap 函数中使用了 mMainOptions。
-
我建议你说:map
mMainOptions;然后调用vectorToMap(vMainOptions, mMainOptions); -
无关:我很确定您不想复制该矢量只是为了将 那个 复制到地图中。也许通过 const-reference 而不是毫无意义的 const-copy 发送它。
-
是您多次尝试正确声明函数的方法之一,即
map<int, string> vectorToMap(const vector<string>& myVector) -
感谢@WhozCraig :) 现在开始工作了