我想重载 [] 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/