cpp_unordered_map - 8BitsCoding/RobotMentor GitHub Wiki

cpp_unordered_map

  • (์ค‘์š”) map๊ณผ unordered_map์˜ ์ฐจ์ด์ ์€ map์€ ์ •๋ ฌ์„ ํ•˜๊ณ (์ด์ง„ํŠธ๋ฆฌ์— ๋”ฐ๋ผ์„œ) unordered_map์€ hash map์— ๋”ฐ๋ผ ์ •๋ ฌ์„ ํ•œ๋‹ค๋Š” ์ .
  • (์ค‘์š”2) ๋‹ค์‹œ ๋งํ•ด์„œ unordered_map์ด๋ผ๊ณ  ํ•ด๋„ ๋„ฃ๋Š”๋ฐ๋กœ ์ €์žฅ๋˜๋Š”๊ฒŒ ์•„๋‹ˆ๋ผ๋Š” ๋ง์ด๋‹ค

๊ทธ๋ƒฅ map์„ ๋ณด์ž

#include <iosream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> scores;

    scores["nono"] = 60;
    scores["Mocha"] = 70;
    scores["coco"] = 100;

    for(auto it = scores.begin(); it != scores.end(); ++it)
    {
        std::cout << it->first << " : " << it->second << std::endl;
    }

    // ์ •๋ ฌ์ด ๋œ ์ƒํƒœ๋กœ ๋‚˜ํƒ€๋‚œ๋‹ค.

    return 0;
}

unordered_map Example

#include <iosream>
#include <unordered_map>
#include <string>

int main() {
    std::unordered_map<std::string, int> scores;

    scores["nono"] = 60;
    scores["Mocha"] = 70;
    scores["coco"] = 100;

    for(auto it = scores.begin(); it != scores.end(); ++it)
    {
        std::cout << it->first << " : " << it->second << std::endl;
    }

    return 0;
}

์ฃผ์˜ ์ด๋ ‡๊ฒŒ ์“ฐ๋ฉด ์ •๋ ฌ๋จ.

#include <iostream>
#include <unordered_map>
using namespace std;

int main() {
	// your code goes here
	unordered_map<int, int> my_map;
	
	my_map.insert(pair<int, int>(5, 1));
	my_map.insert(pair<int, int>(4, 1));
	
	unordered_map<int, int>::iterator it = my_map.begin();
	for(; it != my_map.end(); it++) {
		cout << it->first << endl;
	}
	
	return 0;
}

์ถœ๋ ฅ

4

5


๋‚ด๋ถ€ ๋‚ด์šฉ ๋ณด์—ฌ์ฃผ๊ธฐ

#include <iosream>
#include <unordered_map>
#include <string>

int main() {
    std::unordered_map<std::string, int> scores;

    scores["nono"] = 60;
    scores["Mocha"] = 70;
    scores["coco"] = 100;
    scores["ari"] = 40;
    scores["chris"] = 90;

    for(size_t i = 0; scores.bucket_count(); ++i)
    {
        std::cout << "Bucket #" << i << ": ";
        for(auto it = scores.begin(i); it != scores.end(i); ++it)
        {
            std::cout << " " << it->first << ":" << it->second;
        }

        std::cout << std::endl;
    }

    /*
    Bucket #0:
    Bucket #1: Ari:40 CoCo:100 NaNa60
    Bucket #2:
    Bucket #3:
    Bucket #4:
    Bucket #5: chris:90
    Bucket #6: mocha:70
    Bucket #7:
    */
   // ์ค‘๋ณต๋˜๊ฒŒ ์ €์žฅ์ด ๋˜๊ธฐ๋„ ํ•œ๋‹ค.

    return 0;
}

map VS unordered_map

map

  • ์ž๋™์œผ๋กœ ์ •๋ ฌ๋˜๋Š” ์ปจํ…Œ์ด๋„ˆ
  • ํ‚ค-๊ฐ’ ์Œ๋“ค์„ ์ €์žฅ
  • ์ด์ง„ ํƒ์ƒ‰ ํŠธ๋ฆฌ
  • ํƒ์ƒ‰์‹œ๊ฐ„ O(logn)
  • ์‚ฝ์ž…๊ณผ ์ œ๊ฑฐ๊ฐ€ ๋นˆ๋ฒˆํ•˜๋ฉด ๋А๋ฆฌ๋‹ค

unordered_map

  • ์ž๋™์œผ๋กœ ์ •๋ ฌ๋˜์ง€ ์•Š๋Š” ์ปจํ…Œ์ด๋„ˆ
  • ํ‚ค-๊ฐ’์„ ์Œ๋“ค ์ €์žฅ
  • ํ•ด์‰ฌ ํ…Œ์ด๋ธ”
  • ํƒ์ƒ‰์‹œ๊ฐ„ :
    • O(1) ํ•ด์‰ฌ ์ถฉ๋Œ์ด ์—†๋Š” ๊ฒฝ์šฐ
    • O(n) ์ตœ์•…์˜ ๊ฒฝ์šฐ
  • ๋ฒ„ํ‚ท ๋•Œ๋ฌธ์— ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰ ์ฆ๊ฐ€

โš ๏ธ **GitHub.com Fallback** โš ๏ธ