c++ - 递归 vector 模板

标签 c++ templates vector operator-overloading

我写了下面一段代码:

template<typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
    os << "{";
    for (auto i=v.begin(); i!=v.end(); ++i) {
        os << *i << " ";
    }
    os << "}";
    return os;
}

这适用于常规 vector<int>实例,但我想做的是:

vector<vector<int> > v={{1,2},{3,4}}
cout << v; // Should print {{1 2 } {3 4 } }

相反,我得到了编译错误(以下文本,有一长串候选者):test.cpp|212|error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'std::vector<std::vector<int> >')|

我原以为模板函数可以递归使用两次。我错了吗?如果没有,是什么给了?如果是这样,是否有某种方法可以在不重复代码的情况下使其通用?

最佳答案

 #include <iostream>
 #include <vector>

 template<class T, class A>
 std::ostream& operator<<(std::ostream& os, const std::vector<T,A>& v) {
     os << "{";
     for(auto&&e:v)
       os<<e<<" ";
     os << "}";
     return os;
 }

 int main(){
   std::vector<int> v1{1,2,3};
   std::cout<<v1<<"\n";
   std::vector<std::vector<int>> v2{{1},{2,3}};
   std::cout<<v2<<"\n";
 }

以上代码编译运行。修正你的拼写错误,或者小心你正在使用的命名空间。在当前命名空间或与 ADL 相关的命名空间之外的任何地方重载运算符往往会失败。

关于c++ - 递归 vector 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43429553/

相关文章:

c++ - 为什么 g++ 不能编译元组?

C++ 在 priority_queue 中使用 std::greater() 并排序

javascript - 在 Wordpress 中是否有更简单的方法为多个页面模板排队脚本?

c++ - 将字符串的每个单词插入 vector 并计算每个单词的出现

c++ - Getline 获取 vector 字符串

C++:两个指向相同结构的指针 vector ,每个 vector 的排序不同

c++ - 如果 32 位整数溢出,我们可以使用 40 位结构而不是 64 位长的结构吗?

c++ - 如何检查当前是否用鼠标单击了小部件?

c++ - 模板类规范的简化

c++ - 通过确定系数找到两个 vector 的关系