請教C++有關unordered_map及一個指標的問題
測試環境:Ubuntu、g++ ver.4.4.5
1.
我希望能使用hashtable來存放資料,以string作為key,myClass作為資料內容 (myClass為自己定義的class類型),我查google的結果是C++有hash_map,但無法適用於我這種 的需求,後來又查到有新的方法為unordered_map,但我試著想#include 時編譯產生錯誤:
error This file requires compiler and library support for the upcoming ISO C++ standard, C++0x, This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options.
這是發生什麼問題?我該如何修正?
2.
class A {
int value;
public:
A(int v)
{
value = v;
}
...
};
A test()
{
A* x = new A(55);
return *x;
}
int main()
{
A y = test();
return 0;
}
請問在函式test()中,這種回傳值方式是哪種傳遞方式?有什麼特色?
謝謝各位!
2 個解答
- 其威Lv 710 年前最佳解答
1.
其實 unordered_map 就是 hash_map. 在 C++0x 以前是沒有這東西的。
原本 C++ STL 只有 set, multiset, map, multimap,裡面是一顆 RB Tree。
可是 RB Tree 新增、刪除、搜尋的時間複雜度都是 O(log n),所以增加了使用 hash table 的 hash_set, hash_multiset, hash_map, hash_multimap.
後來決定將 hash 改成 unordered 的原因是,因為 C++ STL 無論是各 container class 主要都以型態或行為命名,而非以實做細節命名。
例如 vector, list, deque 等,他只規定諸如新增、移除、搜尋等動作的複雜度,並不硬性規定實做細節。
所以後來決定將不因採用 hash table 實做而以 hash 命名,而改成描述容器內元素並無特定順序的 unordered_*。
要在 gcc 中使用 unordered_* 或是其他 C++0x 的 feature,你需要在編譯的時候加上 -std=c++0x 或 -std=gnu++0x。
例如:
$ g++ source.cpp -o program
會跟你說
/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.2/include/g++-v4/bits/c++0x_warning.h:31:2: 錯誤:#error This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options.
導致編譯失敗,你可以用
$ g++ -std=c++0x source.cpp -o program
或
$ g++ -std=gnu++0x source.cpp -o program
來編譯。
2.
by value(傳值)
但是這個函式一定會造成 memory-leak。
test() 裡面 new 了一個 A instance, 然後回傳。
main() 中 A y = test(); 會 invoke A 的 copy constructor,用來產生另一個 A instance (y)。
但是這之後 new 出來的那個 instance 就永遠遺失了。
- 匿名使用者7 年前
【亞洲36588合法彩券公司直營 官網: A36588.NET 】
【 最新活動→迎接新會員,首存狂送20% 】
【運動→電子→對戰→現場→彩球 】
【免費服務 →電影區、討論區、KTV歡唱、運動轉播、即時比分、24H客服 】
【亞洲36588合法彩券公司直營 官網: A36588.NET 】