我使用了以下代码,它可以很好地打印带有 printContainer() 的简单 std::vector。
我现在想使用 printContainerV2()
为嵌套容器扩展它
我曾尝试使用模板来确定类型是否为 STL 容器,但它似乎不是执行此操作的方法。
#include <iostream>
#include <iterator>
#include <vector>
template <typename Iter, typename Cont>
bool isLast(Iter iter, const Cont& cont)
{
return (iter != cont.end()) && (next(iter) == cont.end());
}
template <typename T>
struct is_cont {
static const bool value = false;
};
template <typename T,typename Alloc>
struct is_cont<std::vector<T,Alloc> > {
static const bool value = true;
};
template <typename T>
std::string printContainer(T const& container)
{
std::string str = "{";
for (auto it = std::begin(container); it != std::end(container); ++ it)
if (isLast(it, container))
str = str + std::to_string(*it) + "}";
else
str = str + std::to_string(*it) + ",";
return str;
}
/*
template <typename T>
std::string printContainerV2(T const& container)
{
std::string str = "{";
for (auto it = std::begin(container); it != std::end(container); ++ it)
if (isLast(it, container))
if (is_cont<decltype(*it)>::value == true)
str = str + printContainer(*it);
else
str = str + std::to_string(*it) + "}";
else
if (is_cont<decltype(*it))>::value == true)
str = str + printContainer(*it);
else
str = str + std::to_string(*it) + ",";
return str;
}
*/
int main()
{
std::vector<int> A({2,3,6,8});
std::vector<std::vector<int>> M(2,A);
M[1][0] ++;
std::cout << is_cont<decltype(A)>::value << std::endl; // returns true !
for (auto it = std::begin(M); it != std::end(M); ++ it)
{
std::cout << printContainer(*it) << std::endl; // works well std::vector<int>
std::cout << is_cont<decltype(*it)>::value << std::endl; // return false :(
}
// Want to use this for printing a std::vector<std::vector<int>>
// std::cout << printContainerV2(M) << std::endl; // not working !
}
目前,如果代码仅适用于 std::vector 类型和最多一个嵌套级别 (std::vector< std::vector>>) 是可以的。我不确定它是否可以在不努力的情况下通用......
最佳答案
添加#include <type_traits>
header 并替换您的 PrintContainerV2
有了这个:
template<typename T>
using if_not_cont = std::enable_if<!is_cont<T>::value>;
template<typename T>
using if_cont = std::enable_if<is_cont<T>::value>;
template <typename T, typename if_not_cont<T>::type* = nullptr>
std::string printContainerV2(T const& container)
{
std::string str = "{";
for (auto it = std::begin(container); it != std::end(container); ++ it)
if (isLast(it, container))
str = str + std::to_string(*it) + "}";
else
str = str + std::to_string(*it) + ",";
return str;
}
template <typename T, typename if_cont<T>::type* = nullptr>
std::string printContainerV2(T const& container)
{
std::string str = "{";
for (auto it = std::begin(container); it != std::end(container); ++ it)
if (isLast(it, container))
str = str + printContainer(*it) + "}";
else
str = str + printContainer(*it) + ",";
return str;
}
关于c++ - 在 C++ 中以递归方式简单地打印 vector 的 STL vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27594043/