[問題] std::sort??

看板C_and_CPP作者 (Ar藤)時間12年前 (2012/02/23 14:20), 編輯推噓5(505)
留言10則, 5人參與, 最新討論串1/1
test.cpp 檔如下 #include <algorithm> #include <iostream> #include <cstdio> #include <vector> bool cmp(int x , int y ) { return x < y; } int main() { std::vector<int> test; test.push_back( 1 ); test.push_back( 3 ); test.push_back( 2 ); sort( test.begin(), test.end(), cmp ); std::min( 1,2 ); return 0; } 這一段 可以用 g++ test.cpp gcc 4.4.0 gcc 4.5.2 這兩個都可以過 但奇怪的是sort沒加std:: 不知道為什麼還能過 但min就一定要加std:: 請問sort不是在std namespace中是刻意設計的嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 203.192.162.252 ※ 編輯: Arton0306 來自: 203.192.162.252 (02/23 14:29)

02/23 20:28, , 1F
也許在別的standard library也有定義這個function..XD
02/23 20:28, 1F

02/24 06:43, , 2F
test.begin() 回傳 std::vector<int>::iterator 在 std::
02/24 06:43, 2F

02/24 06:44, , 3F
底下, C++ resolving 會因此將 std::sort 納入考慮
02/24 06:44, 3F

02/24 19:50, , 4F
就是所謂的 Koenig lookup
02/24 19:50, 4F

02/24 20:41, , 5F
http://ppt.cc/dyBA 這邊有解釋得很清楚
02/24 20:41, 5F

02/24 20:42, , 6F
ADL對operator有其方便,不過看起來也會帶來一些危險
02/24 20:42, 6F

02/24 20:47, , 7F
簡單說就是參數使用到的namespace也會被納入考量
02/24 20:47, 7F

02/24 20:48, , 8F
所以operator可以不用給namespace也能用
02/24 20:48, 8F

02/24 20:49, , 9F
但是可能因此產生危險,去使用到不對的namespace之函數
02/24 20:49, 9F

02/27 01:36, , 10F
了解了 感謝各位!
02/27 01:36, 10F
文章代碼(AID): #1FHTgZc8 (C_and_CPP)