【发布时间】:2013-12-15 18:43:52
【问题描述】:
有没有更简单的方法可以使用 c++ 将数组转换为集合,而不是循环遍历其元素?
最好使用标准模板库
【问题讨论】:
-
应该提到我对 C++ 很陌生,并且来自 Objective C 背景
有没有更简单的方法可以使用 c++ 将数组转换为集合,而不是循环遍历其元素?
最好使用标准模板库
【问题讨论】:
对于所有标准库容器类型,使用constructor:
std::set<T> set(begin(array), end(array));
【讨论】:
set 的作者很聪明,他们可以应用您不需要学习的各种优化。
s,那么做:s.insert(begin(array), end(array));
int a[] = {1,2,3,4};
std::set<int> s{1,2,3,4};
std::set<int> s1{std::begin(a), std::end(a)};
见:Here
【讨论】:
#include <set>
#include <utility>
#include <iostream>
using namespace std;
auto main()
-> int
{
static int const a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 4};
set<int> const numbers( begin( a ), end( a ) );
for( auto const v : numbers ) { cout << v; }
cout << endl;
}
【讨论】:
如果您想在将数组中的值插入(或插入时)到集合之前对它们执行一些操作,您可以使用 std::transform。
【讨论】:
int arr{} = {1,55,4,2,35,1,5}; //declare the array
int arrSize = sizeof(arr)/sizeof(arr[0]); //get size of the array
set<int> s(arr, arr+arrSize); //move the array to the set ***
【讨论】: