我正在尝试在向量的构造上填充一个vector
(或其他容器)整数序列(与此问题相反)。以下代码可以实现我的预期,将范围构造函数用于,以及Boost的counting_range:vector
#include <iostream>
#include <vector>
#include <boost/range/counting_range.hpp>
using namespace std;
int main () {
vector<int> test_vector(boost::counting_range(2,10).begin(),boost::counting_range(2,10).end());
for (auto i : test_vector) cout << i << endl;
}
问题:
counting_range(2,10).begin()
和counting_range(2,10).end()
?目前,我指定(2,10)的范围两次。编辑:
test_vector=range(2,9)
。在R / Octave / Matlab中,您可以编写test_vector=2:9
或test_vector=seq(2,9,1)
。在这方面,我对上面的内容感到满意。unordered_set test_set(boost::counting_range(2,10).begin(),boost::counting_range(2,10).end());
如果任何解决方案也可以是“与容器无关的”,那就太好了。
动机:
我之所以这样做,是因为我想在我的代码其他地方的有效C ++中服从Meyer的条款4(“确保对象在使用之前已初始化。”)。例如:
class my_class {
public:
my_class()
:vec(boost::counting_range(2,10).begin(),boost::counting_range(2,10).end()) {}
vector<int> vec;
};
不要结束。简单的事情是默认初始化向量,保留并从范围初始化。
确保在使用对象之前将其初始化。
这并不意味着必须在初始化列表中对成员进行完全初始化,而不是my_class
在构造函数完成时必须对对象进行完全初始化。
除此之外,仅出于此目的,您可以在香草C ++中执行不同的操作来处理此问题,例如创建一个辅助函数并按值返回向量:
std::vector<int> create_vector() {
std::vector<int> v;
// ...
return v;
}
但是,仅在需要时,我才不会使用此(或任何其他替代方法)来初始化成员(向量const
可能是足够的借口:))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句