【发布时间】:2016-10-26 21:37:06
【问题描述】:
好的,一个小问题,希望有一个快速、简单的解决方案。
在我的课本中,在关于 STL 的一章中,它提供了一个简单的示例程序,用于输入使用列表和使用带有列表的迭代器,如下所示:
#include <list>
#include <iostream>
#include <string>
using namespace std;
int main()
{
list<int> myIntList;
// Insert to the front of the list.
myIntList.push_front(4);
myIntList.push_front(3);
myIntList.push_front(2);
myIntList.push_front(1);
// Insert to the back of the list.
myIntList.push_back(5);
myIntList.push_back(7);
myIntList.push_back(8);
myIntList.push_back(9);
// Forgot to add 6 to the list, insert before 7. But first
// we must get an iterator that refers to the position
// we want to insert 6 at. So do a quick linear search
// of the list to find that position.
list<int>::iterator i = 0;
for( i = myIntList.begin(); i != myIntList.end(); ++i )
if( *i == 7 ) break;
// Insert 6 were 7 is (the iterator I refers to the position
// that 7 is located. This does not overwrite 7; rather it
// inserts 6 between 5 and 7.
myIntList.insert(i, 6);
// Print the list to the console window.
for( i = myIntList.begin(); i != myIntList.end(); ++i )
cout << *i << " "; cout << endl;
}
现在,在上面写着的那一行
list<int>::iterator i = 0;
我在 VS 2015 中收到一条错误消息:
no suitable constructor exists to convert from"int" to "std::_List_iterator<std::_List_val<std::_List simple_types<int>>>"
提供的代码有什么问题,解决方案是什么,为什么会出现这个问题?
【问题讨论】:
-
“在我的学校教科书中”哇。 Consider getting a better one.
-
std::list没有随机访问迭代器,例如std::vector -
如果学校教科书有这行:list
::iterator i = 0; 我同意你需要一本更好的书。 -
请注意,即使使用矢量(如“
vector<int>::iterator i = 0”)也无法使用 -
天哪,伙计们,这只是一个错字,我认为这不值得“买一本更好的书”cmets,尤其是因为我们甚至不知道实际使用的是什么书。只需从迭代器声明中删除
= 0并继续。