Algorithmic Initializer List?

Is there some way to generate an initializer list algoritmically?

In the case I'm thinking of, I want to initialize a map<> to pair<key, constant> over all expected values of key.

Obviously i could write a loop to initialize after construction, but it would be nice if it could be done in one statement.
> Is there some way to generate an initializer list algoritmically?

No. The only way to construct a non-empty std::initializer_list<> is by using a braced-init-list.


> I want to initialize a map<> to pair<key, constant> over all expected values of key.
> ... it would be nice if it could be done in one statement.

If this kind of initialization is required at many places, an iterator can encapsulate the repetitive code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <complex>
#include <map>
#include <iterator>

using kv_pair_type = std::pair< int, std::complex<double> > ;

template < typename MAP_KEY >
struct kv_pair_iterator : std::iterator< std::input_iterator_tag, const kv_pair_type >
{
    explicit kv_pair_iterator( int k, MAP_KEY mk = MAP_KEY{} )
	    : map_key(mk), pair{ mk(k) } {}

	reference operator*() const { return pair ; }
	pointer operator->() const { return &**this ; }

	kv_pair_iterator& operator++()
	{
	    ++pair.first ;
	    pair = map_key( pair.first ) ;
	    return *this ;
        }

	kv_pair_iterator operator++(int)
	{ kv_pair_iterator temp(*this) ; ++*this ; return temp ; }

	bool operator== ( const kv_pair_iterator& that ) const { return pair == that.pair ; }
	bool operator!= ( const kv_pair_iterator& that ) const { return pair != that.pair ; }

	private:
	    const MAP_KEY map_key ;
	    kv_pair_type pair ;
};

template < typename MAP_KEY >
kv_pair_iterator<MAP_KEY> make_kvpi( int key, MAP_KEY map_key = MAP_KEY{} )
{ return kv_pair_iterator<MAP_KEY>{ key, map_key } ; }

int main ()
{
    struct make_kvpair
    { 
        kv_pair_type operator() ( int key ) const 
        { return { key, std::complex<double>( key*3 + 2, key*key ) } ; } 
    };

    using iterator = kv_pair_iterator<make_kvpair> ;

    std::map< int, std::complex<double> > map { iterator(1), iterator(10) } ;

    for( const auto& p : map ) std::cout << p.first << " => " << p.second << '\n' ;
}

http://coliru.stacked-crooked.com/a/5cc6937268b7b8c7
Topic archived. No new replies allowed.