[英]What is the most efficient way of accessing elements in a C++ container?
假設我想依次訪問C ++容器中的所有元素,哪種方式最有效? 我在下面的例子中說明了我的問題:
std::vector<int> abc;
abc.push_back(3);
abc.push_back(4);
...
...
for(int i=0; i<abc.size(); i++)
{
abc[i];
}
std::vector<int>::iterator it = abc.begin();
std::vector<int>::iterator itEnd = abc.end();
while(it != itEnd)
{
(*it);
it++;
}
在這個例子中,正如您所看到的,兩個方法用於訪問C ++容器中的元素,因此一個自然的問題是哪一個更有效。 謝謝。
想出這個問題的最好方法是做一些像100萬個循環一樣的測試。 編譯器各不相同。 確保在發布模式下進行測試。
我使用ACE,但這里是我如何獲得時差的一個例子。
// Log how long each module takes.
ACE_Time_Value lSendStart;
ACE_Time_Value lDifference;
// Start keeping track of how long this takes
lSendStart = ACE_OS::gettimeofday();
// Figure out how long we took.
lDifference = ACE_OS::gettimeofday() - lSendStart;
// Log how long we took
PLALOG_INFO( mLogger, ACE_TEXT( "doProcessing took ") <<lDifference.sec () << ACE_TEXT( "seconds(s) and ") << (lDifference.usec ()) <<
ACE_TEXT(" micro second(s) to process." ), "" );
因此,獲取開始時間,循環一百萬次,獲得差異,然后以相反的方式執行相同的循環。
我發現的另一件事,如果你可以使用c ++ 11中的auto,你通常會發現一個更快的循環,然后像你所示的那樣找到歷史悠久的for循環。
std::vector<std::string> lNameList;
// fill in vector
for(auto& lSection : lNameList)
{
// lSection is not a string
// DO something with it
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.