You cannot directly come up with std :: vector to std :: string or vice versa. But using the iterators provided by STL containers allows you to iterate over a vector and a string equally. And if your function requires random access to the container in question, then it will either work.
std::vector<char> str1 {'a', 'b', 'c'}; std::string str2 = "abc"; template<typename Iterator> void iterator_function(Iterator begin, Iterator end) { for(Iterator it = begin; it != end; ++it) { std::cout << *it << std::endl; } } iterator_function(str1.begin(), str1.end()); iterator_function(str2.begin(), str2.end());
Both of these last two function calls will print the same thing.
Now, if you want to write a generic version that parses only characters stored only in a string or in a vector, you could write something that repeats the internal array.
void array_function(const char * array, unsigned length) { for(unsigned i = 0; i < length; ++i) { std::cout << array[i] << std::endl; } }
Both functions will do the same in the following scenarios.
std::vector<char> str1 {'a', 'b', 'c'}; std::string str2 = "abc"; iterator_function(str1.begin(), str1.end()); iterator_function(str2.begin(), str2.end()); array_function(str1.data(), str1.size()); array_function(str2.data(), str2.size());
There are always many ways to solve a problem. Depending on what you have, any number of solutions can work. Try both and see which one is best for your application. If you do not know the type of iterator, then you need an iteration of the char array. If you know that you will always have a template type for transferring, then the template template method may be more useful.