我正在查看一些 C++ 文档,这时我突然想到 vector 容器没有构造函数可以“轻松”允许用户传递一系列值(最小值和最大值)并构造 vector 其中包含从最小值到最大值的元素。我认为这很奇怪,所以我尝试自己编写并发现它很重要。这是我的解决方案。
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
template <typename T>
class MyIterator: public std::iterator<std::input_iterator_tag, int>
{
public:
MyIterator(T val):value(val) {}
MyIterator(const MyIterator & m):value(m.value) {}
MyIterator& operator ++()
{
++value;
return *this;
}
MyIterator operator ++(int)
{
MyIterator temp(*this);
operator ++();
return temp;
}
bool operator ==(const MyIterator & m) const { return value == m.value; }
bool operator !=(const MyIterator & m) const { return !(value == m.value); }
T& operator *() { return value; }
private:
T value;
};
int main(int argc, char** argv)
{
std::vector<int> my_vec(MyIterator<int>(100), MyIterator<int>(400));
std::copy(my_vec.begin(), my_vec.end(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
新的 C++ 对此有解决方案吗?
最佳答案
在 C++11 中有 std::iota
功能。否则你有例如std::fill
和 std::fill_n
, 或 std::generate
和 std::generate_n
.
关于C++ vector 范围构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20841775/