将可变大小元素列表添加到向量的语法糖?
我有一个包含向量的类:
class Foo {
typdef std::vector<int> Vec;
Vec m_kids;
void addKids(Vec::const_iterator begin,
Vec::const_iterator end) {
m_kids.insert(m_kids.end(), begin, end);
}
};
有什么方法可以允许以下简洁的函数调用吗? (也许通过更改上面的 addKids
函数?)
int main() {
Foo foo;
foo.addKids(23,51,681); // these...
foo.addKids(3,6,1,4,88,2,4,-2,101); // ...would be nice?!
}
我怀疑您可以使用 C++0x 向量初始值设定项列表来做到这一点?但不幸的是,我不能使用C++0x。不过,如果有帮助的话,我可以使用 Boost。
I have a class that contains a vector:
class Foo {
typdef std::vector<int> Vec;
Vec m_kids;
void addKids(Vec::const_iterator begin,
Vec::const_iterator end) {
m_kids.insert(m_kids.end(), begin, end);
}
};
Is there any way to allow the following concise function calls? (Maybe by changing the addKids
function above?)
int main() {
Foo foo;
foo.addKids(23,51,681); // these...
foo.addKids(3,6,1,4,88,2,4,-2,101); // ...would be nice?!
}
I suspect you can do it with C++0x vector initializer lists? But unfortunately, I cannot use C++0x. I can use Boost, though, if that helps.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以这样做:
为此,您必须重载
<<
和,
运算符,如下所示:一旦实现了此操作,您还可以编写:
即使这样,
或者将两者混合为:
全部相同!
但混合起来效果不太好。我的偏好是第一个!
You can do this:
For that you've to overloaded
<<
and,
operators, as:Once you implement this, then you can also write:
Even this,
Or mix both as:
All are same!
But mixing doesn't look good. My preference is the very first one!
语法不是 100% 相同,但请查看 boost 的 list_of: http://www.boost.org/doc/libs/1_47_0/libs/assign/doc/index.html#list_of
Not 100% the same syntax, but check out boost's list_of: http://www.boost.org/doc/libs/1_47_0/libs/assign/doc/index.html#list_of
我不知道有任何 boost 功能可以做到这一点(很可能只是因为我还没有看到它,“boost has it”几乎是一个公理......),但是您可以定义一个可变参数函数来执行此操作。它看起来像这样:
I'm not aware of any boost functionality that does this (most likely just because I haven't seen it yet, "boost has it" is almost an axoim...), but you could define a variadic function that does it. It'd look something like this:
如果您更改迭代器类型
,那么您至少可以这样做:
这看起来非常简洁。
If you change your iterator types
then you can at least do this:
Which seems pretty concise.