vector::empty ,vector::end , vector::erase

vector::empty


// vector::empty
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
  vector<int> myvector;
  int sum (0);
  for(int i=1;i<=10;i++) myvector.push_back(i);
  while (!myvector.empty())
  {
     sum += myvector.back();
     myvector.pop_back();
  }
  cout << "total: " << sum << '\n';  //输出 total: 55 

  return 0;
}

vector::end


// vector::begin/end
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
   vector<int> myvector;
  for (int i=1; i<=5; i++) myvector.push_back(i);
  
  vector<int>::iterator it; 
  
  cout << "myvector contains:";
  for ( it = myvector.begin() ; it != myvector.end(); ++it)
    cout << ' ' << *it;
    cout << '\n';
  return 0;
}
//Output:
//myvector contains: 1 2 3 4 5

vector::erase


// erasing from vector
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
    vector<int> myvector;
  // set some values (from 1 to 10)
  for (int i=1; i<=10; i++) myvector.push_back(i);

  // erase the 6th element
  myvector.erase (myvector.begin()+5);

  // erase the first 3 elements:
  myvector.erase (myvector.begin(),myvector.begin()+3);

   cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size(); ++i)
    cout << ' ' << myvector[i];
    cout << '\n';

  return 0;
}

//Output:
//myvector contains: 4 5 7 8 9 10




已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页