【发布时间】:2012-04-15 20:53:50
【问题描述】:
我正在尝试编写一个将通用列表转换为向量的函数,但是,我无法编译我的函数。这是我的代码(位于 .h 文件中):
template <class T>
inline std::vector<T> list2vector(std::list<T> &l)
{
std::vector<T> v;
v.insert(v.begin(),l.begin(),l.end());
return v;
}
谁能指出我在这里遗漏了什么? 编译错误如下:
find_rpeat.cpp:85: error: invalid initialization of non-const reference of type
?std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >&?
from a temporary of type
?std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >?
【问题讨论】:
-
函数签名中可能需要
const std::list<T>? -
这段代码为我编译http://ideone.com/p3CEt
-
能否贴出调用函数编译失败的代码?
-
请注意,有一个
vector构造函数接受一个范围:std::vector<T>(l.begin(), l.end()); -
@user788171:你能发布调用函数吗?看起来
mylist是const std::list<string>&或者您尝试调用它的函数是const函数。