views:

275

answers:

2

I'm coding in C++

What is the shortest function of:

template<T> std::vector<T> make_copy(const deque<T>& d) {
  // your code here
}

?

+5  A: 

return std::vector<T>(d.begin(), d.end());?

GMan
It's gonna be hard to top that :)
Eric Pi
C++0x to the rescue: `return{d.begin(),d.end()};` :)
Johannes Schaub - litb
@litb: Bah, cheater. :P
GMan
A: 

Can't really compete with UncleBens in terms of program length so instead I'll post the most general solution to the problem:

template<class Src>
struct CopyMaker {

    Src const & src;

    CopyMaker(Src const & src) : src(src) {
    }

    template<class Dest>
    operator Dest() const {
        return Dest(src.begin(), src.end());
    }
};

template<class Src>
CopyMaker<Src> make_copy(Src const & src) {
    return CopyMaker<Src>(src);
}

int main()
{
    std::vector<int> vec;
    std::deque<int> deq = make_copy(vec);
    std::list<int> list = make_copy(deq);
    std::set<int> set = make_copy(list);
}
Manuel