gpt4 book ai didi

c++ 为 std::pair 重载 operator[]

转载 作者:太空狗 更新时间:2023-10-29 20:00:00 26 4
gpt4 key购买 nike

我经常使用值对:std::pair<int, int> my_pair .有时我需要对 my_pair.first 执行相同的操作和 my_pair.second .

如果我能做到 my_pair[j] 我的代码会更流畅并遍历 j=0,1。(我避免使用数组,因为我不想为分配内存而烦恼,并且我将 pair 广泛用于其他事情)。

因此,我想定义 operator[]对于 std::pair<int, int> .

而且我无法让它工作,(我不太擅长使用模板等)...

#include <utility>
#include <stdlib.h>

template <class T1> T1& std::pair<T1, T1>::operator[](const uint &indx) const
{
if (indx == 0)
return first;
else
return second;
};

int main()
{
// ....
return 0;
}

编译失败。其他变体也会失败。

据我所知,我正在关注 Stack Overflow operator overloading FAQ ,但我想我遗漏了一些东西......

最佳答案

  1. 您不能将 operator[] 作为非成员重载
  2. 你不能定义一个没有在类定义中声明的成员函数
  3. 不能修改 std::pair 的类定义

这是一个非成员实现:

/// @return the nth element in the pair. n must be 0 or 1.
template <class T>
const T& pair_at(const std::pair<T, T>& p, unsigned int n)
{
assert(n == 0 || n == 1 && "Pair index must be 0 or 1!");
return n == 0 ? p.first: p.second;
}

/// @return the nth element in the pair. n must be 0 or 1.
template <class T>
T& pair_at(std::pair<T, T>& p, unsigned int index)
{
assert(index == 0 || index == 1 && "Pair index must be 0 or 1!");
return index == 0 ? p.first: p.second;
}

// usage:
pair<int, int> my_pair(1, 2);
for (int j=0; j < 2; ++j)
++pair_at(my_pair, j);

请注意,我们需要两个版本:一个用于只读对,一个用于可变对。

不要害怕随意使用非成员函数。正如 Stroustrup 自己所说,没有必要用一个对象来模拟一切,也没有必要通过继承来扩充一切。如果您确实想使用类,请选择组合而不是继承。

你也可以这样做:

/// Applies func to p.first and p.second.
template <class T, class Func>
void for_each_pair(const std::pair<T, T>& p, Func func)
{
func(p.first);
func(p.second);
}

/// Applies func to p.first and p.second.
template <class T, class Func>
void for_each_pair(std::pair<T, T>& p, Func func)
{
func(p.first);
func(p.second);
}

// usage:
pair<int, int> my_pair(1, 2);
for_each_pair(my_pair, [&](int& x){
++x;
});

如果您有 C++11 lambda 表达式,那么使用它并不会太笨拙,而且至少更安全一些,因为它不可能越界访问。

关于c++ 为 std::pair 重载 operator[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9526430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com