Home > Net >  In C how do I insert strings into a set?
In C how do I insert strings into a set?

Time:03-17

#include <iostream>
#include <iomanip>
#include <string>
#include <set>

int main(){
    
    std::string text;
    std::getline(std::cin, text);
    
    std::set<std::string> filter;
    
    for(int i = 0; i< text.length(); i  ){
        filter.insert(text[i]);
    }
}

I'm getting an error with my code, it says:

no known conversion for argument 1 from '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' {aka 'char'} to 'std::initializer_list<std::__cxx11::basic_string<char>>'

Do I need to convert each one into a char, then insert into the set?

CodePudding user response:

You are trying to insert individual char values into a std::set of std::string values, thus set::insert() is expecting you to give it either a std::string or a std::initializer_list<std::string> as input. But neither one of those can be constructed from a single char, hence the error.

However, std::string does have another constructor that takes a char and a count as input, eg:

std::set<std::string> filter;
    
for(int i = 0; i < text.length(); i  ){
    filter.insert(std::string(1, text[i]));
}

Otherwise, create a std::set of char values instead:

std::set<char> filter;
    
for(int i = 0; i < text.length(); i  ){
    filter.insert(text[i]);
}

CodePudding user response:

text[i] is a character not a string,

if you are trying to chop up the input into several word you need to do that yourself.

If thats what you want then either

  • use cin>>word in a loop , this will pick out individual words for you, rather than getline which reads the whole input as one string
  • create a stringstream over text and use ss>>word on that
  • or walk down text char by char skipping white space (the fiddlyest way)
  • Related