您不能直接将 std::vector 类型转换为 std::string,反之亦然。但是使用 STL 容器提供的迭代器确实允许您以相同的方式迭代向量和字符串。如果您的函数需要随机访问相关容器,那么任何一个都可以工作。
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());
最后两个函数调用都会打印相同的内容。
现在,如果您想编写一个仅解析仅存储在字符串或向量中的字符的通用版本,您可以编写一些迭代内部数组的东西。
void array_function(const char * array, unsigned length)
{
for(unsigned i = 0; i < length; ++i)
{
std::cout << array[i] << std::endl;
}
}
这两个函数在以下场景中会做同样的事情。
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());
解决问题总是有多种方法。根据您可用的内容,任何数量的解决方案都可能有效。尝试两者,看看哪个更适合您的应用程序。如果您不知道迭代器类型,那么 char 类型的数组迭代很有用。如果你知道你总是需要传入模板类型,那么模板迭代器方法可能会更有用。