I am inserting vector values into set. After that i am trying to print set values where i get compilation issues. please help me to understand what i am doing wrong.
code:
#include<iostream>
#include<set>
#include<vector>
using namespace std;
int main()
{
set<string> s1;
vector<string> v1;
v1.push_back("Hello");
v1.push_back("Hello");
v1.push_back("Hi");
v1.push_back("Hi");
v1.push_back("Cya");
for(int i=0; i<v1.size(); i++)
{
s1.insert(v1[i]);
}
for(int i= 0; i<s1.size(); i++)
{
cout<<s1[i]<<endl;
}
return 0;
}
compilation error:
error: no match for ‘operator[]’ (operand types are ‘std::set<std::basic_string<char> >’ and ‘int’)
cout<<s1[i]<<endl;
You use the iterator interface:
for (std::set<std::string>::const_iterator it = s1.begin(), end = s1.end();
it != end; ++it) {
std::cout << *it << '\n';
}
You could also use std::copy
:
std::copy(s1.begin(), s1.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));