Vector of structs

I have written the following code to sort a vector of structs

Out put of below code is like this:
RANK: 7----papu
RANK: 7----hen
RANK: 8----pavi
RANK: 10----avi
RANK: 15----cucu
RANK: 20----kimi
RANK: 20----miki


What I want to do is display only similar ranked data
RANK: 7----papu
RANK: 7----hen
RANK: 20----kimi
RANK: 20----miki


Can someone please advise

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
  #include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;



struct st
{
	int rank;
	std::string name;
	bool operator() (st i, st j) { return (i.rank<j.rank); }

};


int _tmain(int argc, _TCHAR* argv[])
{
	st obj0;
	obj0.rank = 20;
	obj0.name = "kimi";

	st obj1;
	obj1.rank = 7;
	obj1.name = "papu";
	
	st obj2;
	obj2.rank = 10;
	obj2.name = "avi";

	st obj3;
	obj3.rank = 8;
	obj3.name = "pavi";

	st obj4;
	obj4.rank = 7;
	obj4.name = "hen";

	st obj5;
	obj5.rank = 15;
	obj5.name = "cucu";

	st obj6;
	obj6.rank = 20;
	obj6.name = "miki";

	typedef std::vector<st> myvec;
	myvec myvect1;
	myvec myvect2;
	myvect1.push_back(obj0);
	myvect1.push_back(obj1);
	myvect1.push_back(obj2);
	myvect1.push_back(obj3);
	myvect1.push_back(obj4);
	myvect1.push_back(obj5);
	myvect1.push_back(obj6);


	std::sort(myvect1.begin(), myvect1.end(), st());
		

	for (auto x : myvect1)
		{
			std::cout << "  RANK: " << x.rank <<"----"<< x.name << endl;
		}

}
Last edited on
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
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>

struct st
{
    int rank;
    std::string name;
    double hight;

    bool operator< ( st that ) const { return rank < that.rank ; }
    bool operator== ( st that ) const { return rank == that.rank ; }
    // ...
};

int main()
{
    std::vector<st> seq = { { 20, "kimi", 1 }, { 7, "papu", 2 }, { 10, "avi", 3 },
            { 8, "pavi", 4 }, { 7, "hen", 5 }, { 15, "cucu", 6 }, { 20, "miki", 7 } } ;

    std::sort( seq.begin(), seq.end() ) ;
    
    // http://en.cppreference.com/w/cpp/algorithm/adjacent_find
    for( auto iter = std::adjacent_find( seq.begin(), seq.end() ) ;
         iter != seq.end() ;
         iter = std::adjacent_find( iter, seq.end() ) )
    {
        for( int rank = iter->rank ; iter != seq.end() && rank == iter->rank ; ++iter )
             std::cout << "RANK: " << rank << " ---- " << iter->name << '\n' ;
        std::cout << '\n' ;     
    }
}

http://coliru.stacked-crooked.com/a/5a8724daa4bd0843
Last edited on
Topic archived. No new replies allowed.