最近,我利用<numeric> iota语句递增了一个int类型的向量。但是现在我尝试使用这个语句来增加一个包含两个成员的显式类。
下面是整数向量的用法:
vector<int> n(6);
iota(n.begin(), n.end(), 1);考虑到Obj类有一个名为m的整数成员。构造函数将m初始化为其相应的整数参数。以下是我现在要做的事:
vector<Obj> o(6);
iota(o.begin(), o.end(), {m(1)});我尝试使类增量重载类似于以下内容:
Obj& operator ++() {
*this.m++;
return *this;
}但我认为我的构造函数不是为这种重载而设计的,反之亦然。如何修改构造函数和重载以使用iota增加对象成员?提前感谢!
发布于 2014-10-27 01:04:34
我不太明白你的问题。下面的代码与您想要的匹配吗?
#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 10.7.4上用gcc 4.8编译,我得到:
$ g++ iota-custom.cpp -std=c++11
$ ./a.out
0
1
2
3
4
5
6
7
8
9发布于 2014-10-27 01:08:17
更新:我更改了答案,以提供注释中要求的功能:即能够更新多个字段。
以类似于以下方式设置类的格式。您需要重载++操作符以同时增加_m和_c。
class Obj {
private:
int _m;
char _c;
public:
Obj(int m, char c) : _m(m), _c(c)
{
}
MyClass operator++()
{
_m++;
_n++;
return *this;
}
};下面的代码将用6 o初始化向量Obj,每个Obj包含从1开始的_m和_c的升序值。
vector<Obj> o(6);
iota(o.begin(), o.end(), Obj(1, 1));发布于 2014-10-27 01:10:26
#include <numeric> // std::iota
#include <vector>
using namespace std;
class Obj
{
private:
int m_;
public:
auto value() const -> int { return m_; }
Obj( int m = 0 ): m_( m ) {}
};
auto main() -> int
{
vector<Obj> v(6);
iota( v.begin(), v.end(), 1 );
}https://stackoverflow.com/questions/26579703
复制相似问题