I have this Question in my Uni Home work.could std:list-char be converted to std:list-int in c++.I hope to get right Answers from you as soon as possible.

1 Answers

Yksisarvinen On

It's not possible to do it in a trivial way, like this:

std::list<char> charList {1, 2, 3, 4};
std::list<int> int list = charList; //compiler error

But you can reconstruct list as an std::list<int> "manually" (see it online):

std::list<char> charList {1, 2, 3, 4};
std::list<int> intList(charList.begin(), charList.end());

When using the iterator constructor of std::list, there's only one conversion for compiler to perform: char -> int. One implicit conversion is perfectly fine, so it works. But std::list<char> and std::list<int> are completely unrelated types from compiler point of view, so it doesn't know how to convert one to another.