类C ++的Iota增量向量 [英] iota increment vector of a class c++
问题描述
我最近一直在利用< numeric>
iota
语句来增加类型 int
。但是现在我试图使用该语句来增加具有2个成员的显式类。
I recently have been taking advantage of the <numeric>
iota
statement for incrementing a vector of type int
. But now I am trying to use the statement for incrementing an explicit class with 2 members.
所以这是整数向量的用法:
So here is the usage with a vector of integers:
vector<int> n(6);
iota(n.begin(), n.end(), 1);
鉴于 Obj
类具有整数成员称为 m
。构造函数将 m
初始化为其相应的整数参数。这是我现在要执行的操作:
Given that Obj
class has an integer member called m
. The constructor initializes m
to its corresponding integer argument. Here is what I am trying to do now:
vector<Obj> o(6);
iota(o.begin(), o.end(), {m(1)});
我试图使类增量重载有点像这样:
I've attempted making a class increment overload somewhat like this:
Obj& operator ++() {
*this.m++;
return *this;
}
但是我认为我的构造函数不是为这种重载而设计的,反之亦然。如何修改构造函数和重载以使用iota递增对象成员?
But I think either my constructor is not designed for this overload or vice versa. How can I modify my constructor and overload to increment an object member with iota? Thanks in advance!
推荐答案
我不确定我是否理解您的问题。以下代码是否符合您的要求?
I am not sure I understand your question. Does the following code match what you want?
#include <algorithm>
#include <iostream>
#include <vector>
class Object {
public:
Object(int value = 0)
: m_value(value) { }
Object& operator++() {
m_value++;
return *this;
}
int value() const {
return m_value;
}
private:
int m_value;
};
int main() {
std::vector<Object> os(10);
std::iota(os.begin(), os.end(), 0);
for(const auto & o : os) {
std::cout << o.value() << std::endl;
}
}
在OS X 10.7.4上使用gcc 4.8编译得到:
Compiled with gcc 4.8 on OS X 10.7.4 I get:
$ g++ iota-custom.cpp -std=c++11
$ ./a.out
0
1
2
3
4
5
6
7
8
9
这篇关于类C ++的Iota增量向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!