1. 程式人生 > >stl 中怎樣遍歷一個map中的所有元素。請給是例項

stl 中怎樣遍歷一個map中的所有元素。請給是例項

兩 種方式iterator遍歷的次數是相同的,但在STL中效率不同,前++--返回引用,後++--返回一個臨時物件,因為iterator是類模板,使 用it++這種形式要返回一個無用的臨時物件,而it++是函式過載,所以編譯器無法對其進行優化,所以每遍歷一個元素,你就建立並銷燬了一個無用的臨時 物件。

不信的話你可以去看看C++的標準庫,還有符合標準C++的教材,除了特殊需要和對內建型別外,基本都是使用++it來進行元素遍歷的,不管是原始碼還是教材中都是如此。

使用者定義型別對操作符的過載應與內建操作符的行為相似,而且後自增/減往往是引用前自增/減來作為其實行的一個副本。

比如通常都是這種形式:

class foo
{
public:
foo& operator ++ (){return ++bar;}

foo operator ++ (int)
{
foo tmp = *this; // 建立臨時物件 ★
++*this; // 呼叫前自增
return tmp; // 返回臨時物件 ★
}

private:
int bar;
}

以上標★號的2個步驟有時是多餘的,比如用STL中用iterator遍歷容器,這樣就造成了不必要的程式效率的損失。

這也是被一些從C移植到C++的程式設計師所頻頻忽視的細節,所以它們被稱為從C帶到C++中的程式設計惡習。

More Effective C++
Item 6: Distinguish between prefix and postfix forms of increment and decrement operators.

對C++中的前/後自增/減操作符以及因C++的過載對他們所引發的效率問題有詳細的講解。以下是一部分內容:

If you're the kind who worries about efficiency, you probably broke into a sweat when you first saw the postfix increment function. That function has to create a temporary object for its return value (see Item 19), and the implementation above also creates an explicit temporary object (oldValue) that has to be constructed and destructed. The prefix increment function has no such temporaries. This leads to the possibly startling conclusion that, for efficiency reasons alone, clients of UPInt should prefer prefix increment to postfix increment unless they really need the behavior of postfix increment. Let us be explicit about this.

When dealing with user-defined types, prefix increment should be used whenever possible, because it's inherently more efficient. (注意這一句)

Let us make one more observation about the prefix and postfix increment operators. Except for their return values, they do the same thing: they increment a value. That is, they're supposed to do the same thing. How can you be sure the behavior of postfix increment is consistent with that of prefix increment? What guarantee do you have that their implementations won't diverge over time, possibly as a result of different programmers maintaining and enhancing them? Unless you've followed the design principle embodied by the code above, you have no such guarantee. That principle is that postfix increment and decrement should be implemented in terms of their prefix counterparts. You then need only maintain the prefix versions, because the postfix versions will automatically behave in a consistent fashion.