Is it possible to concatenate two vectors then sort the elements by an object variable of each element in the vector?

Hi,

So I guess this is two fold:
How do I merge two vectors?

Then:
How do I sort vector elements by one of their object variables?
(I have a method defined in the object class to return the variable to be sorted by)
Last edited on
I don't think theres a standard function for merging two vectors, though that would be cool.

I guess what I would do is just something like

1
2
3
4
i=0
while(vector1 does not have all elements from vector2)
vector1.push_back(vector2[i];
i = i + 1
I managed to concatenate them.
Now how can I sort by an object variable?
Depends on the variable type and how you want it sorted.
For sorting a std::vector<> it would make sense to use std::sort. To use sort on a vector of objects you need to implement either a comparator function and pass it to sort or overload operator< for your object.
http://www.cplusplus.com/reference/algorithm/sort/
Last edited on
> How do I merge two vectors?
> How do I sort vector elements by one of their object variables?
> (I have a method defined in the object class to return the variable to be sorted by)

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
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>

struct A
{
    int value() const { return v ; }
    const std::string& str() const { return s ; }

    int v ;
    std::string s ;
};

void foo( std::vector<A>& first, std::vector<A>& second )
{
    std::vector<A> third ;
    // merge first and second into third ordered on v
    auto cmp = [] ( const A& a, const A& b ) { return a.value() < b.value() ; } ;
    std::sort( first.begin(), first.end(), cmp ) ; // sort first on ascending v
    std::sort( second.begin(), second.end(), cmp ) ; // sort second on ascending v
    std::merge( first.begin(), first.end(), second.begin(), second.end(),
                std::back_inserter(third), cmp ) ; // merge first and second into third

    // append contents of second to first
    first.insert( first.end(), second.begin(), second.end() ) ;

    // sort first on descending length of str
    std::sort( first.begin(), first.end(),
               [] ( const A& a, const A& b ) { return a.str().size() > b.str().size() ; } ) ;
}
Last edited on
Topic archived. No new replies allowed.