2012-04-02 17 views
1

ジェネリックリストをベクターに変換する関数を作成しようとしていますが、コンパイルする関数を取得できません。以下は私のコード(.hファイルの中にあります)です:C++でベクターテンプレートを返すことができません

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> > > >? 
+1

たぶん、あなたは、関数のシグネチャで 'のconstのstd ::リスト'を必要ですか? – arrowd

+0

このコードは私のためにコンパイルされました[http://ideone.com/p3CEt](http://ideone.com/p3CEt) – ks1322

+0

wow、constを追加すると、そのトリックができました。 – user788171

答えて

3
std::vector<T> v; 
std::copy(l.begin(),l.end(), std::back_inserter(v)); 
0

すでにSTLにあなたのための変換関数を、一般的な存在です。あなたはSTLを使用していることを行うことができれば、私はlist2vectorまたは他の何かを書くためにどのような理由が表示されない

std::transform(l.begin(), l.end(), std::back_inserter(v), Fn);

試してみてください。 2つの「汎用」セット間のマッピングのように考えてください。リストとベクトルの間のあなたの場合。 (非への一時的なオブジェクトを割り当てるvector<string>& myvector = list2vector(mylist);:あなたのコードのご意見をもとに

1

はそのようなもので、それはコンパイルする必要があります

#include <iostream> 
#include <vector> 
#include <list> 
using namespace std; 

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; 
} 

int main() { 
    list<string> mylist; 
    vector<string> myvector = list2vector(mylist); 
    return 0; 
} 

をしかし、あなたのエラーメッセージを生成するために、のようなものがあるはず私はあなたが1行

std::vector<T> v (l.begin(), l.end()); 

そして、C++ 11にはさえ短いを行うことができます中にベクトルを作成し、埋めることができますように見えるconst参照)

0
template <class T> 
inline std::vector<T> list2vector(std::list<T> &l) 
{ 
    return {l.begin(), l.end()}; 
}