问题
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);
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;
}
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!
回答1:
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;
}
}
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
回答2:
Updated: I changed the answer to provide the functionality requested in the comments: namely, to be able to update multiple fields.
Format your class in a manner similar to the following. You will need to overload the ++
operator to increment both _m
and _c
.
class Obj {
private:
int _m;
char _c;
public:
Obj(int m, char c) : _m(m), _c(c)
{
}
MyClass operator++()
{
_m++;
_n++;
return *this;
}
};
The following code will initialize the vector o
with 6 Obj
's, each containing ascending values for _m
and _c
starting from 1.
vector<Obj> o(6);
iota(o.begin(), o.end(), Obj(1, 1));
回答3:
#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/iota-increment-vector-of-a-class-c