迭代器“指向”到对象的成员
我承认我很难对此做出合理的描述。我想不出一个好的术语来准确描述我正在寻找的东西。也许这可以称为切片迭代器。
假设我有这样的东西:
struct S
{
int i;
char *s;
float f;
};
std::vector<S> v(10);
我正在寻找一种构造迭代器的方法,它将指向 S
的成员。我希望能够将其传递给诸如 std::min_element 之类的东西,而无需在每种情况下创建谓词。可能看起来像这样:
std::min_element(slicing_iterator(v.begin(), S::f), slicing_iterator(v.end(), S::f));
是否有任何模板技巧可以用来实现此目的?或者也许它已经在 Boost 或其他库中完成了?
I admit I had difficulties coming up with a reasonable description for this. I cannot think of a good term that would describe precisely what I'm looking for. Perhaps this could be called a slicing iterator.
Let's say I have something like this:
struct S
{
int i;
char *s;
float f;
};
std::vector<S> v(10);
What I'm looking for is a way to construct an iterator, that would point to a member of S
. I'd like to be able to pass it to something like std::min_element
without creating a predicate in each case. Something that might look like this:
std::min_element(slicing_iterator(v.begin(), S::f), slicing_iterator(v.end(), S::f));
Is there any template trick that I could use to achieve this? Or perhaps it's already done somewhere in Boost or some other library?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您正在寻找一个将 S 转换为其 S::f 的迭代器,这当然可以使用 boost 来完成(什么不能?):
test: https://ideone.com/jgcHr
但是,如果您正在寻找 S::f 是向量中最小的 S,则谓词是最合理的方法。
If you're looking for an iterator that converts S into its S::f, this could certainly be done using boost (what can't be?):
test: https://ideone.com/jgcHr
But if you're looking for the S whose S::f is the smallest in the vector, the predicate is the most reasonable approach.
如果您不想为每种情况创建谓词函数,我建议不要寻找切片运算符,而是将谓词实现为 lambda 函数(使用 Boost 或 C++0x)。在这里您可以找到详细的解释
http://www.codeproject.com/KB/cpp/ Sort.aspx
(这是关于
std::sort
的,但std::min_element
中的比较同样有效。)If you don't want to create a predicate function for each case, I would suggest not to look for a slicing operator, but to implement your predicate as a lambda function (either using Boost or C++0x). Here you will find a detailed explanation
http://www.codeproject.com/KB/cpp/Sort.aspx
(this is about
std::sort
, but the comparison instd::min_element
works equally.)像这样的东西可以完成工作吗?
Will something like this do the job?
除了已经建议的内容之外,您还可以像代码示例那样几乎完全一样地进行操作。
示例:
起初我没有注意到 - 它看起来与 @Stuart Golodetz 建议的类似,但优点是运算符<不必为迭代器类型定义(例如 std::list::iterator)。它使这个实现具有普遍性。
In addition to what is already suggested you may do it almost exactly like your code sample does.
Example:
At first I didn't notice - it looks similar to what @Stuart Golodetz suggested but the advantage is that operator< doesn't have to be defined for iterator type (e.g. std::list::iterator). It makes this implementation universal.