1

大家好,有什么方法可以使用向量迭代器返回向量中的前 5 个元素?

在这个例子中,我得到的只是向量本身的所有值。

// 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;
}

嗯,感谢所有及时回复.. 但是为什么当我尝试将它们放入函数时会出现编译错误?

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()));
}
4

3 回答 3

3

前进myvector.begin()5

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

这最多打印前 5 个元素myvector

这里

参考: - std::copy, std::min, 和std::ostream_iterator

于 2013-10-27T05:19:47.717 回答
1
#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;
}
于 2013-10-27T05:20:45.103 回答
1

std::vector 支持随机访问迭代器,这意味着您可以这样做:

myvector.begin() + 5

因此,您的代码有两个选择:

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];

或者

auto startIt = myvector.begin();
auto endIt = myvector.begin() + 5;
for (auto it = startIt; it != endIt; ++it)
  std::cout << ' ' << *it;
于 2013-10-27T05:53:09.240 回答