Is there a more elegant way to initialise from two vectors of pairs at the same time

I have a vector of pairs of characters, I want to initialize the first and last
pair with the first values of two other vectors of pairs of < char, float> called RFoL and RFoSL

so I got this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    //loops for RFoL
    for(auto &c : RFoL){

        //adds first char of RFoLtemporary char
        keyMap.push_back(std::pair<char, char>( c.first, '-'));
    }

    int x = 0;

    //loops for RFoSL and adds second value to keyMap
    for(auto &c : RFoSL){

        //adds temporary char
        keyMap.at(x).second = c.first;
        x++;
    }


but I know there's a better way that's well ugly, something like this
1
2
3
4
5
for(auto &x : std::vector<std::pair<char, float>>::const_iterator){

    keyMap.push_back(RFoL[x].first, RFoSL[x].first);
}


or maybe some tasty lambdas, dont know how to write that beautiful, Im looking foward to revising for c++ exam, going to start right from the start again
for(size_t K=0; K<std::min(RFoL.size(), RFoSL.size()); ++K)
Not directly, but you can write something that makes it so.

http://www.cplusplus.com/forum/beginner/64872/#msg352608
ne555 is good enough for how im iterating, when ones longer than the other I stop anyway, to be clear, K is the size of each object and im iterating through them.

Thas nice code Duoas, im going to need to go through things like this, will have an exam on c++ in june!!
Ja this worked perfectly!! thanks :D

1
2
3
4
for(size_t K = 0; K < std::min(RFoL.size(), RFoSL.size()); ++K){

         keyMap.push_back(std::pair<char, char>( RFoL[K].first, RFoSL[K].first));
    }


so much more beautiful, ima go study lambdas now.
Last edited on
Boost also provides a useful drop-in if you want to stick to iterators over indexed lookups.

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
#include <iostream>
#include <iterator>
#include <utility>
#include <vector>

#include <boost/range/algorithm_ext/for_each.hpp>
#include <boost/range/iterator_range.hpp>

int main()
{
  char  cs[] = { 'a', 'b', 'c' };
  float fs[] = { 1.0, 2.0, 3.0, 4.0 };
  
  std::vector <std::pair <char, float> > cfs;
  
  using std::begin;
  using std::end;
  boost::for_each(
    boost::make_iterator_range( begin(cs), end(cs) ),
    boost::make_iterator_range( begin(fs), end(fs) ),
    [&cfs]( char c, float f )
    {
      cfs.push_back( std::make_pair( c, f ) );
    } );
    
  for (auto cf : cfs)
    std::cout << cf.first << "," << cf.second << "\n";
}

Topic archived. No new replies allowed.