[英]Can we make a map in C++, with the value as a function of key?
在C ++ STL中,映射用於將鍵映射到值。 我想知道我們是否可以根據一些功能說來做這種映射
map <int,string> M;
和value = binary_representation(key)?
, ( )) pairs for a function and any 1 , …, you like, provided that the types match. 您可以在std::map
插入任意( key , value )對,因此您當然可以為函數和任意 1 ,…, 插入( , ( ))對,只要類型匹配。
直接執行此操作的方法可能是使用for
循環。
for (const auto& k : keys)
mapping[k] = f(k);
這是一個完整的示例:
#include <climits>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
namespace /* anonymous */
{
std::string
my_function(const int n)
{
const auto size = static_cast<int>(CHAR_BIT * sizeof(int));
std::string bits {};
for (auto i = 0; i < size; ++i)
{
const auto bit = (n >> (size - i - 1)) & 1;
bits += (bit ? '1' : '0');
}
return bits;
}
}
int
main()
{
std::map<int, std::string> reprs {};
for (auto k = -3; k < 10; ++k)
reprs[k] = my_function(k);
for (const auto& kv : reprs)
std::cout << std::setw(4) << kv.first << " => " << kv.second << '\n';
}
可能的輸出:
-3 => 11111111111111111111111111111101
-2 => 11111111111111111111111111111110
-1 => 11111111111111111111111111111111
0 => 00000000000000000000000000000000
1 => 00000000000000000000000000000001
2 => 00000000000000000000000000000010
3 => 00000000000000000000000000000011
4 => 00000000000000000000000000000100
5 => 00000000000000000000000000000101
6 => 00000000000000000000000000000110
7 => 00000000000000000000000000000111
8 => 00000000000000000000000000001000
9 => 00000000000000000000000000001001
如果您想遵循std::insert_iterator
於原始循環的算法的建議,則可以將std::transform
與std::insert_iterator
一起使用來完成此任務。
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <map>
#include <string>
#include <utility>
#include <vector>
namespace /* anonymous */
{
std::string
my_function(int); // as above
}
int
main()
{
std::vector<int> keys(13);
std::iota(keys.begin(), keys.end(), -3);
std::map<int, std::string> reprs {};
const auto generator = [](const int n){
return std::make_pair(n, my_function(n));
};
std::transform(keys.cbegin(), keys.cend(),
std::inserter(reprs, reprs.begin()),
generator);
for (const auto& kv : reprs)
std::cout << std::setw(4) << kv.first << " => " << kv.second << '\n';
}
但是,在這種簡單情況下,我不確定使用迭代器和算法是否真的有助於代碼的可讀性。 這里使用keys
向量有點令人討厭。 如果您擁有Boost,可以將其替換為boost::counting_iterator
。
您可以這樣做,但這將完全沒有意義。 它只是劣等的std::set<int>
,不能正確地保證不變性,並且消耗更高的內存使用量和運行時間,而絲毫沒有任何好處(除非您確實想要緩存)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.