简体   繁体   中英

return top 5 value using vector iterator

Hi all is there any way to return the first 5 element in a vector using vector iterator?

In this example I've got it will only all value in the vector itself.

// vector::begin/end
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;
  for (int i=1; i<=10; i++) myvector.push_back(i);

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

hmmm thanks for all the prompt reply.. but why am I having compilation error when I try to put them in a function?

void Test::topfives()
{   
    topfive.assign( point1.begin(), point1.end() ); 
    sort(topfive.begin(), topfive.end(), sortByCiv);
}

void Test::DisplayTopFiveResult()
{
    test.topfives();

    copy(topfive.begin(), topfive.begin()+ min(topfive.size(), (size_t )5),
    ostream_iterator<Level>(cout << level.displayClassresult()));
}

Advance the myvector.begin() by 5

std::copy(myvector.begin(), 
          myvector.begin()+std::min(myvector.size(), (size_t)5), 
          std::ostream_iterator<int>(std::cout,"\n"));

This prints at max top 5 elements from myvector

See Here

Ref: - std::copy , std::min , and std::ostream_iterator

#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;
  for (int i=1; i<=10; i++) myvector.push_back(i);

  std::cout << "myvector contains:";
  std::vector<int>::iterator it = myvector.begin()
  for (int i = 0; i < 5 && it != myvector.end(); i++) {
    std::cout << ' ' << *it;
    ++it;
  }
  std::cout << '\n';

  return 0;
}

std::vector supports random access iterators , which means you can do this:

myvector.begin() + 5

So two options for your code:

std::cout << "myvector contains:";
size_t maxElements = std::min(myvector.size(), size_t(5));
for (size_t i = 0; i < numElements; ++i) {
  std::cout << ' ' << myvector[i];

or

auto startIt = myvector.begin();
auto endIt = myvector.begin() + 5;
for (auto it = startIt; it != endIt; ++it)
  std::cout << ' ' << *it;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM