vector中數據進行去重和排序

int a[] = {3, 2, 3, 5, 7, 5, 9 ,2};
std::vector<int> vec(a, a+sizeof(a)/sizeof(int) );
std::sort(vec.begin(), vec.end() );
vector<int>::iterator iter_end;
iter_end = std::unique(vec.begin(), vec.end() );
vec.erase(iter_end, vec.end() );

 對以下函數一一說明:ios

sort:從小到大排序。程序執行到sort後的結果:函數

unique:元素去重,unique返回重複元素開始的位置,而且會改變原vec的向量值。程序執行到unique後的結果(輸出此時的Vec):spa

earse:刪除元素。程序執行到erase後的結果(輸出此時的Vec):3d

完成對vector的去重和排序code

 

另外說明vertor的幾個屬性blog

capacity:系統如今給vector分配的內存大小排序

size:vector現有的數據大小內存

max_size:系統能夠給給vector分配的最大容量ci

// comparing size, capacity and max_size
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;

  // set some content in the vector:
  for (int i=0; i<100; i++) myvector.push_back(i);

  std::cout << "size: " << (int) myvector.size() << '\n';
  std::cout << "capacity: " << (int) myvector.capacity() << '\n';
  std::cout << "max_size: " << (int) myvector.max_size() << '\n';
  return 0;
}
結果:
size: 100
capacity: 128
max_size: 1073741823

再給個例子補充一下erase的用法:it

// vector_erase.cpp
// compile with: /EHsc
#include <vector>
#include <iostream>

using namespace std;

int main()
{
      
   vector <int> vec;
    vector <int>::iterator pos;

    vec.push_back(10);
    vec.push_back(20);
    vec.push_back(30);
    vec.push_back(40);
    vec.push_back(50);

    cout << "Capacity = " << vec.capacity() << endl;
    cout << "vec =";
    for (pos = vec.begin(); pos != vec.end(); ++pos)
    {
        cout << " " << *pos;
    }        
    cout << endl;

    vec.erase(vec.begin());
    cout << "vec = ";
    for (pos = vec.begin(); pos != vec.end(); ++pos)
    {
        cout << " " << *pos;
    }
    cout << endl;

    vec.erase(vec.begin() + 1, vec.begin() + 3);
    cout << "vec = ";
    for (pos = vec.begin(); pos != vec.end(); ++pos)
    {
        cout << " " << *pos;
    }     
    cout << endl;
    cout << "Capacity after erase calls = " << vec.capacity() << endl;
}
結果:
Capacity = 6
vec = 10 20 30 40 50
vec = 20 30 40 50
vec = 20 50
Capacity after erase calls = 6來源:https://msdn.microsoft.com/en-us/library/ceh559x2.aspx
相關文章
相關標籤/搜索