You can traverse through the string and insert each character into the set:
#include <iostream>
#include <set>
int main()
{
std::string text;
std::cin>> text;
std::set<char> yeet;
for(char c:text)
yeet.insert(c);
std::cout<< yeet.size();
}
However, its not necessary to write a loop to insert into a set container. A much simpler approach would be to use std::set::insert()
with two iterator positions as @idclev463035818 mentioned, or directly constructing the set at the time of declaration using a constructor.
Consider the loop approach as an alternative.
Additionally, you can change iterator positions if you want to get elements from specific parts of the string. (loop works too, but the former includes shorter code)
Remember that a set holds distinct elements, so only the unique ones would be inserted and correspondingly account for total size.
Edit:
Based on the string having characters apart from the alphabets, with your requirement being to take only the alphabets, (a, b, c and d in your example) you can use issalpha()
.
A more generic approach, to include only the character you desire (even alphabets or any character in general) can be followed by creating a function (of boolean type) which distinguishes those characters and provides the same information to std::remove_if
(include <algorithm>
), to erase those elements (again, following the erase-remove-idiom) via a std::erase
from your string:
bool IsValid(char c) { return(c == '{' || c == '}' || c == ',' || c == ' '); }
Working example:
#include <iostream>
#include <set>
#include <algorithm>
bool IsValid(char c) { return(c == '{' || c == '}' || c == ',' || c == ' '); }
int main()
{
std::string text = {"{a, b, c, d}"};
text.erase(std::remove_if(text.begin(), text.end(), IsValid), text.end());
std::set<char> yeet(text.begin(),text.end());
std::cout << yeet.size();
}
Output: 4