如何使函数参数容器独立 [英] How to make function argument container independent
问题描述
我写了一个实用函数,它将获取一个元素(可以是字符串,int,double,char)的向量,并连接成一个单一的字符串并返回它。它看起来像这样:
I'm writing a utility function which will take a vector of elements (could be string, int, double, char) and concatenate into a single string and return it. It looks like this:
template<typename T>
std::string convert2Str(std::vector<T> const& vec)
{
std::ostringstream sStream;
for (size_t k=0; k<vec.size(); ++k) {
sStream << vec[k] << " ";
}
return sStream.str();
}
我想让这个函数更通用:
I would like to make this function more generic:
- 首先使用迭代器,而不是使用
向量< T>
的索引。我试过这个
std :: vector< T> :: const_iterator it = vec.begin()
循环之前,编译器给我一个错误:
:error:expected;
之前
当我将上面的定义更改为std :: vector< std :: string> ;: :const_iterator it = vec.begin()
错误消失。所以,看起来我没有遵循正确的语法,请让我知道它是什么 - 第二是通过使第一个参数容器独立使函数更通用。给定任何容器(
向量
,列表
,队列
code> deque 等)我想做同样的事情。我尝试在stackoverflow搜索这个,没有找到满意的答案。
- First use iterators instead of using indices for the
vector<T>
. I tried thisstd::vector<T>::const_iterator it = vec.begin()
before the loop and the compiler gave me an error: : error: expected;
before it When I change the above defintions tostd::vector<std::string>::const_iterator it = vec.begin()
the error goes away. So, it looks like I'm not following correct syntax, please let me know what it is - Second is to make the function more generic by making the first argument container independent. Given any container (
vector
,list
,queue
,deque
, etc.) I want to do the same thing as above. I tried searching for this in stackoverflow and did not find satisfactory answer.
推荐答案
正如你所说,使用迭代器:
Step 1, as you said, use iterators:
template<typename T>
std::string convert2Str(std::vector<T> const& vec)
{
typedef std::vector<T> container;
std::ostringstream sStream;
for (typename container::const_iterator it = vec.begin(); it != vec.end(); ++it) {
sStream << *it << " ";
}
return sStream.str();
}
步骤2,使模板参数为容器类型而不是元素类型您可以使用 value_type
获得元素类型:
Step 2, make the template argument the container type instead of the element type (you can get the element type back with value_type
:
template<typename container>
std::string convert2Str(container const& vec)
{
typedef container::value_type T; // if needed
std::ostringstream sStream;
for (typename container::const_iterator it = vec.begin(); it != vec.end(); ++it) {
sStream << *it << " ";
}
return sStream.str();
}
++ 0x,这变得更简单(并且不需要 typename
):
In C++0x, this gets even simpler (and typename
is not needed):
template<typename container>
std::string convert2Str(container const& vec)
{
using std::begin;
using std::end;
std::ostringstream sStream;
for (auto it = begin(vec); it != end(vec); ++it) {
typedef decltype(*it) T; // if needed
sStream << *it << " ";
}
return sStream.str();
}
除了其他优点, std :: begin
和
std :: end
用于原始数组。
Among other advantages, std::begin
and std::end
work for raw arrays.
这篇关于如何使函数参数容器独立的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!