标准库类的自定义赋值操作符



例如,如果我想赋值

std::vector<int> a;
std::vector<std::pair<std::string, int>> b;
a = b;  // a takes all the second components of the pairs in b

这样的自定义赋值可能吗?

您似乎想要的是转换一个容器到另一个。这通常通过适当命名的std::transform标准函数来完成:

std::vector<int> a(b.size());  // Set as same size as the source vector
std::transform(begin(b), end(b), begin(a), [](auto const& pair)
{
return pair.second;  // Use the second value of each pair from the source
});

是否可以重载=以使a = b;second的所有元素都推到a上?

。除了std类型重载操作符的其他问题外,=只能作为成员函数实现。不能为std::vector<int>添加成员。


是否可以重载=以使a = b;second的所有元素推送到a?

是的。你不能为std::vector重载=,但是你可以为不同的类型重载它:

#include <vector>
#include <utility>
#include <string>

struct pick_second_vector_ref {
std::vector<int>& t;
template <typename Source>
void operator=(const Source& s) {
for (const auto& e : s) {
t.push_back(e.second);
}
}
};
int main() {
std::vector<int> a;
std::vector<std::pair<std::string, int>> b {{"foo",42}};
pick_second_vector_ref r{a};
r = b;  // a takes all the second components of the pairs in b
}

然而,这只是为了说明当你的问题太字面化时会发生什么。通常,命名函数比操作符重载要清晰得多。上面的main应该看起来像这样:

int main() {
std::vector<int> a;
std::vector<std::pair<std::string, int>> b {{"foo",42}};
copy_second(a,b); // no comment needed here because the code 
// explains itself !!
}

ps…

我在很多地方使用了=,现在我已经改变了左向量操作数,我将不得不在我使用=的地方放置必要的转换函数。

Ok。大胆去做吧。更改代码。这将是简单的修复,因为代码中出现的所有=都是编译器错误。记住:代码只写一次,但要多次阅读。从长远来看,当读者不必怀疑=实际上做了什么时,你花在修复=上的5分钟将节省下来(注释应该只需要在代码无法清晰表达时解释代码,而不是这里的情况)。

最新更新