@NooooN
Секьюрник, гык. Лавки вебчик за 300.

Как вывести последние n элементов map?

Нужно вывести последние 5 элементов map, как это сделать?
  • Вопрос задан
  • 1283 просмотра
Решения вопроса 3
Nipheris
@Nipheris Куратор тега C++
#include <string>
#include <map>
#include <algorithm>
#include <iostream>
 
int main() {
    std::map<int, std::string> m {
        { 1, "one" },
        { 2, "two" },
        { 3, "three" },
        { 4, "four" },
        { 5, "five" },
        { 6, "six" },
        { 7, "seven" },
        { 8, "eight" },
        { 9, "nine" },
        { 10, "ten" },
    };
 
    auto from = m.end();
    // откатываемся назад на 5 элементов (возможно есть способ покрасивее)
    for (int i = 0; i < 5; i++) {
    	from--;
    }
 
    std::for_each(from, m.end(), [](auto&& pair) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    });
}


https://ideone.com/bUps4b
Ответ написан
Комментировать
Therapyx
@Therapyx
Data Science
#include <iostream>
#include <string>
#include <map>

using namespace std;

int main() {

  map<string, int> m_test;

  m_test.insert(pair<string, int>("A", 100));
  m_test.insert(pair<string, int>("B", 200));
  m_test.insert(pair<string, int>("C", 300));
  m_test.insert(pair<string, int>("D", 400));
  m_test.insert(pair<string, int>("E", 500));

  map<string, int>::iterator iter;

  iter = m_test.end();
  int lastValues = 3;
  while (lastValues != 0) {
	  iter--; lastValues--;
	  cout << iter->first << ", " << iter->second << endl;
  }

  system("pause");
  return 0;
}
Ответ написан
Комментировать
Taraflex
@Taraflex
Ищу работу. Контакты в профиле.
https://ideone.com/ARMZ7G
#include <iostream>
#include <map>
#include <string>

int main() {
	std::map<int,std::string> m = {
		{1,"1"},
		{2,"2"},
		{3,"3"},
		{4,"4"},
		{5,"5"},
		{6,"6"},
		{7,"7"},
		{8,"8"},
	};
	int i = 0;
	for(auto it = --m.end();it != m.begin();--it,++i){
		if(i>4){break;}
		std::cout << it->first << ':' << it->second <<std::endl;
	}
	
	return 0;
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы