std::sort

Oct 28, 2017 at 9:43pm
my compiler doesnt like the way im doing std::vector and std::map for my sort is there any way to do it with just map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 std::vector< std::pair<std::string,student>> map;
	std::map<std::string, student>::const_iterator it;
	for(it = m_student.begin(); it != m_student.end(); it++)
    {
        map.push_back(*it);
    }
    std::sort(map.begin(),map.end(),[](std::pair<std::string,student> &a,std::pair<std::string,student> &b)
              {
                  return a.second < b.second;//i get and error here

              }

            );
Last edited on Oct 28, 2017 at 10:40pm
Oct 28, 2017 at 9:49pm
You can't sort an std::map. An std::map is always sorted according to its keys.
If you need the items in an std::map sorted by a different criterion then you need to copy them somewhere else (like onto a vector) and sort them there.
Oct 28, 2017 at 9:54pm
would you use copy() and how would you do that?
Oct 28, 2017 at 10:33pm
Oops. My bad, I misread your code. I thought map was an std::map instead of an std::vector. You should avoid doing stuff like that.
1
2
std::map<int, int> string;
std::string pointer;
You should preferably name containers based on what data they contain; failing that, you should name them according to the type that they are, especially if the function is going to handle multiple containers.

return a.second < b.second;//i get and error here
Never say "an error". If you get an error then say what error you're getting. We can't look at your screen.
Last edited on Oct 28, 2017 at 10:33pm
Oct 28, 2017 at 10:41pm
ok
Oct 30, 2017 at 11:49am
This looks a question for clairvoyants: how to guess what’s wrong in a code without seeing the code and the error messages?

Hints:
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
#include <algorithm>
#include <iostream>
#include <limits>
#include <string>
#include <vector>

struct Student { int id {}; };
void waitForEnter();

using Namestud = std::pair<std::string, Student>;

int main()
{
    std::vector<Namestud> map { { "Barbara", {2} }, { "Carol", {3} }, {"Ann", {1} } };
    std::sort(map.begin(), map.end(),
                [] (Namestud &a, Namestud& b) { return a.second.id < b.second.id; }
              );
    for(const auto& a : map) {
        std::cout << a.first << ' ' << a.second.id << '\n';
    }
    waitForEnter();
    return 0;   
}

void waitForEnter()
{
    std::cout << "\nPress ENTER to continue...\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

Output:
Ann 1
Barbara 2
Carol 3

Press ENTER to continue...

Topic archived. No new replies allowed.