STL常用技巧

來源:互聯網
上載者:User

1,刪除一個元素

比如:vector vecID; 中儲存了m個ID,這時要刪除第n個ID。

遍曆是一個方法;即vector::itertor it = vecID.begin(); 然後++it n次。

更好的方法是:vector::itertor it = vecID.begin() + n; vector的迭代器直接支援這種位移。

然後用vecID.erase(it)方法 刪除該元素。

 

2.去除一個容器中有特定值的所有對象

1)如果容器是vector、string或deque,使用erase-remove慣用法,例如

c.erase(remove(c.begin(), c.end(), 1963),c.end());

 

2)如果容器是list,使用list.remove

// 當c是list時,remove成員函數是去除特定值的元素的最佳方法

c.remove(1963);

 

3)如果容器是標準關聯容器,使用它的erase成員函數,例如:

// 當c是標準關聯容器時,erase成員函數是去除特定值的元素的最佳方法

c.erase(1963);

 

3.去除一個容器中滿足一個特定判定式的所有對象

 bool badValue(int x);   // 函數定義:返回x是否是“bad”

o     如果容器是vector、string或deque,使用erase-remove_if慣用法:

// 當c是vector、string或deque時這是去掉badValue返回真的對象的最佳方法

c.erase(remove_if(c.begin(), c.end(), badValue),c.end());

o     如果容器是list,使用list.remove_if:

// 當c是list時這是去掉badValue返回真的對象的最佳方法

c.remove_if(badValue);

o     如果容器是標準關聯容器,使用remove_copy_if和swap。

o     如果需要寫一個迴圈遍曆容器元素erase,注意iterator的遞增邏輯

// 錯誤碼:當容器的一個元素被刪時,指向那個元素的所有迭代器都失效了

AssocContainer<int> c;

// 不要這麼做!

for (AssocContainer<int>::iterator i = c.begin(); i!= c.end(); ++i)

{                                          

    if (badValue(*i))

    {

        c.erase(i);

    }

}

 

// 正確代碼:

AssocContainer<int> c;

// for迴圈的第三部分是空的,i在後面自增。

for (AssocContainer<int>::iterator i = c.begin(); i != c.end();)

{

    if (badValue(*i))

    {

        i = c.erase(i); //僅適用序列容器,關聯容器用c.erase(i++); 因關聯容器erase 返回void,

    }

    else

    {

        ++i;

    }

}(#add 妙哉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.