Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to set in C++

Tags:

c++

arrays

set

Is there an easier way to turn an array in to a set using c++ rather than looping through its elements?

Preferably using the standard template library

like image 733
Adam Carter Avatar asked Dec 15 '13 18:12

Adam Carter


People also ask

Can we convert array into Set?

Therefore the Array can be converted into the Set with the help of Collections. addAll() method.

How do you pass an array to a Set in C++?

Convert an array to Set using begin() and end() In this method, we use STL function to convert begin() and end() to convert pointers to iterators. Then we will pass the iterators to set constructor to convert an array to a set. In this example we converted an array to a set in C++.

Can we change elements in array in C?

you can change the integers pointed at directly via the * operator, so *array = 99; will change the first element, *(array+1) = 98; the second and so on. you can also, more naturally use the [] operator. so in your function array[0] = 99; will actually change the original array. Save this answer.

How do you convert an array to a number?

To convert an array of strings to an array of numbers, call the map() method on the array, and on each iteration, convert the string to a number. The map method will return a new array containing only numbers.


3 Answers

As for all standard library container types, use the constructor:

std::set<T> set(begin(array), end(array));
like image 114
Konrad Rudolph Avatar answered Nov 06 '22 04:11

Konrad Rudolph


int a[] = {1,2,3,4};
std::set<int> s{1,2,3,4};

std::set<int> s1{std::begin(a), std::end(a)};

See: Here

like image 27
P0W Avatar answered Nov 06 '22 03:11

P0W


#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;
}
like image 24
Cheers and hth. - Alf Avatar answered Nov 06 '22 04:11

Cheers and hth. - Alf