如何仅在n次打印多页图中的元素

时间:2022-04-19 07:35:09

My multimap has an int as a key and a string as the value. The key is the number of times a word has occurred and the value is the word itself. I figured that if I loop through the multimap with my iterator at rbegin and rend, I can just loop through it ten times rather than until it reaches the end to find the top ten words. Any idea how to do this?

我的multimap有一个int作为键,一个字符串作为值。关键是单词出现的次数,值是单词本身。我想如果我在rbegin和rend中使用我的迭代器遍历multimap,我可以循环遍历它十次而不是直到它到达结尾才能找到前十个单词。知道怎么做吗?

2 个解决方案

#1


1  

Sure! Here's one option:

当然!这是一个选项:

unsigned numTimes = 0;
for (auto itr = myMultiMap.rbegin();
     itr != myMultiMap.rend() && numTimes < kMaxTimes;
     ++itr, ++numTimes) {

    /* Do something with itr */

}

#2


1  

Another option would be to use std::advance to find the tenth item (starting from rbegin). With that, you get a valid range, and you can process it with the usual algorithms and such:

另一个选择是使用std :: advance来找到第十个项目(从rbegin开始)。有了它,您将获得一个有效的范围,您可以使用通常的算法处理它,例如:

std::map<int, std::string> word_freqs;

auto first = word_freqs.rbegin();
auto last = std::next(first, 10);

Now, we can (for example) print out those 10 most common words:

现在,我们可以(例如)打印出这10个最常见的单词:

typedef std::pair<int, std::string> T;

std::ostream &operator<<(std::ostream &os, T const &t) { 
    return os << t.second << ": " << t.first;
}

std::copy(first, last, std::ostream_iterator<T>(std::cout, "\n"));

Of course, for robustness, you'd probably want to include a check that the multimap has at least 10 items first (and probably just use rbegin() and rend() if it's smaller than that).

当然,为了实现稳健性,您可能希望包含一个检查,即multimap首先至少有10个项目(如果它小于那个,可能只使用rbegin()和rend())。

#1


1  

Sure! Here's one option:

当然!这是一个选项:

unsigned numTimes = 0;
for (auto itr = myMultiMap.rbegin();
     itr != myMultiMap.rend() && numTimes < kMaxTimes;
     ++itr, ++numTimes) {

    /* Do something with itr */

}

#2


1  

Another option would be to use std::advance to find the tenth item (starting from rbegin). With that, you get a valid range, and you can process it with the usual algorithms and such:

另一个选择是使用std :: advance来找到第十个项目(从rbegin开始)。有了它,您将获得一个有效的范围,您可以使用通常的算法处理它,例如:

std::map<int, std::string> word_freqs;

auto first = word_freqs.rbegin();
auto last = std::next(first, 10);

Now, we can (for example) print out those 10 most common words:

现在,我们可以(例如)打印出这10个最常见的单词:

typedef std::pair<int, std::string> T;

std::ostream &operator<<(std::ostream &os, T const &t) { 
    return os << t.second << ": " << t.first;
}

std::copy(first, last, std::ostream_iterator<T>(std::cout, "\n"));

Of course, for robustness, you'd probably want to include a check that the multimap has at least 10 items first (and probably just use rbegin() and rend() if it's smaller than that).

当然,为了实现稳健性,您可能希望包含一个检查,即multimap首先至少有10个项目(如果它小于那个,可能只使用rbegin()和rend())。