I need to know can initialize a set using loop and how?
What should i make in this code?
#include <iostream>
#include <set>
using namespace std;
int main()
{
set <char>s;
for (auto it = s.begin(); it != s.end();it++){
cin >>*it;
}
return 0;
}
I'm going to assume you want to loop over all the user input. Note that the simplest way I have shown will ignore whitespace.
#include <iostream>
#include <set>
int main()
{
std::set<char> s;
char c; // input from user
while (std::cin >> c) { // read until end of input
s.insert(c);
}
// do something with s, I guess?
}
This: std:cin >> c
will fail when the user finishes their input, which will terminate the loop. I'll repeat myself: std::cin >>
skips whitespace . If you want to also read any whitespace characters the user inputs, I can show a way to do that too.
Iterators only let you access items that are already in the std::set
(or other container), and in the case of std::set
you can't assign to things once they are in there.
Please also note that using namespace std;
is widely considered to be bad practice .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.