C++ 重载 [] 使用模板访问子 vector

标签 c++ templates vector operator-overloading

我想重载 [] vector 运算符以轻松创建临时子 vector 。

我认为它会类似于下面显示的代码。但是,当我尝试编译时出现错误:

error: "operator[]" must be a member function

哪个 [] 是 vector 的成员。

#include <vector>
#include <algorithm>

using namespace std

template <class T, int a, int b>
T& operator[](int a, int b)
{
    vector<class T> subvector;
    copy ( T.begin() + min(a, b), v1.begin() + max(a, b) + 1, back_inserter(subvector) );

    if (a > b) {reverse(subvector.begin(), subvector.end());};
}

最佳答案

虽然有些运营商喜欢 operator+operator>>可以作为带有特定数量参数的独立函数存在,operator[]不能。它必须是类的成员函数。

你试图实现的目标也无法完成,因为 operator[]只能接受一个参数。

只需使用一个函数:

template<typename T>
std::vector<T> make_sub_vector(std::vector<T> const& v, int begin, int end) {
    assert(begin < end); // Either this, or you swap them 
                         // if this condition is not met.
                         // I'm asserting because I don't know 
                         // what to do when they're equal.
    return std::vector<T>(v.begin() + begin, v.begin() + end);
}

关于C++ 重载 [] 使用模板访问子 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25410510/

相关文章:

python - 如何向量化 `__call__`方法

c++ - 在c/c++中初始化未知大小的数组

c++ - 检查文件是否被进程文件句柄锁定

c++ - 默认 move 构造函数和引用成员

c++ - GCC 7 没有选择正确的类型特征特化

c++ - 如果我们使用 SFINAE 匹配类型,则完全失败

c++ - 如何找到 2 张 map 中所有常见的键?

c++ - 直接结构初始化

c++ - 模板的多态使用

c++ - 调试 vector 检索?