C ++:使用来自其他静态初始化容器的数据静态初始化容器
C++: Statically initialize container with data from other statically initialized container
有没有办法将一个静态初始化容器的 keys/values 映射到另一个静态初始化容器?类似的东西:
#include <iostream>
#include <set>
using namespace std;
const set< pair< string, int > > my_set = {
( "three" , 3 ),
( "seven" , 7 ),
( "twelve", 12 )
};
//how to statically extract pairs' first values?
const set< string > my_strings = my_set.values().map( []( const auto & pair ){ return pair.first; } );
int main() {
cout << "statically initialized set:" << endl;
for ( const auto & v : my_strings )
cout << " " << v << endl;
}
预期输出:
statically initialized set:
three
seven
twelve
范围-v3:
const set< string > my_strings =
my_set
| ranges::views::keys
| ranges::to<std::set>();
views::keys
在 C++20 中,但 ranges::to
不是。
不需要特殊的图书馆或c++20
#include <iostream>
#include <set>
using namespace std;
const set< pair< string, int > > my_set = {
{ "three" , 3 },
{ "seven" , 7 },
{ "twelve", 12 }
};
//how to statically extract pairs' first values?
const set< string > my_strings = []{
set<string> data;
for(auto& pair: my_set){ // or with c++20 : ranges & use set's InputIt constructor
data.insert(pair.first);
}
return data;
}();
int main() {
cout << "statically initialized set:" << endl;
for ( const auto & v : my_strings )
cout << " " << v << endl;
}
请注意 std::set
没有 constexpr 构造函数,它不会进行 compile-time 初始化。
有没有办法将一个静态初始化容器的 keys/values 映射到另一个静态初始化容器?类似的东西:
#include <iostream>
#include <set>
using namespace std;
const set< pair< string, int > > my_set = {
( "three" , 3 ),
( "seven" , 7 ),
( "twelve", 12 )
};
//how to statically extract pairs' first values?
const set< string > my_strings = my_set.values().map( []( const auto & pair ){ return pair.first; } );
int main() {
cout << "statically initialized set:" << endl;
for ( const auto & v : my_strings )
cout << " " << v << endl;
}
预期输出:
statically initialized set:
three
seven
twelve
范围-v3:
const set< string > my_strings =
my_set
| ranges::views::keys
| ranges::to<std::set>();
views::keys
在 C++20 中,但 ranges::to
不是。
不需要特殊的图书馆或c++20
#include <iostream>
#include <set>
using namespace std;
const set< pair< string, int > > my_set = {
{ "three" , 3 },
{ "seven" , 7 },
{ "twelve", 12 }
};
//how to statically extract pairs' first values?
const set< string > my_strings = []{
set<string> data;
for(auto& pair: my_set){ // or with c++20 : ranges & use set's InputIt constructor
data.insert(pair.first);
}
return data;
}();
int main() {
cout << "statically initialized set:" << endl;
for ( const auto & v : my_strings )
cout << " " << v << endl;
}
请注意 std::set
没有 constexpr 构造函数,它不会进行 compile-time 初始化。