extracting data from std::set<string>

  • Thread starter Rene Ivon Shamberger
  • Start date
R

Rene Ivon Shamberger

I am trying to extract data from a set container, but to no avail. This is what I have done.
int main(){
std::set<const std::string> data;
data.insert("one");
data.insert("two");
data.insert("three");
int counter = 0;

std::set<std::string>::iterator it;
for (it = data.begin(); it != data.end(); it++) {
counter++;
std::cout << *it;
}
return 0;
}
 
R

Rui Maciel

Rene said:
I am trying to extract data from a set container, but to no avail. This is
what I have done. int main(){
std::set<const std::string> data;
data.insert("one");
data.insert("two");
data.insert("three");
int counter = 0;

std::set<std::string>::iterator it;
for (it = data.begin(); it != data.end(); it++) {
counter++;
std::cout << *it;
}
return 0;
}


here's your problem:
std::set<const std::string> data;

The STL allocates objects using C++'s allocators, which only store non-
const, non-reference object types. You are trying to allocate a const-
object type. Hence, the flood of compiler errors you should be getting from
this.

Replace the above with:

std::set<std::string> data;

and everything will work fine.

While you are at it, use const iterators to enforce the object's const-ness.
So, replace:

std::set<std::string>::iterator it;

with


std::set<std::string>::const_iterator it;


Hope this helps,
Rui Maciel
 
S

SG

Am Freitag, 19. Oktober 2012 16:35:45 UTC+2 schrieb Rene Ivon Shamberger:
I am trying to extract data from a set container, but to no avail.
This is what I have done.

int main(){
std::set<const std::string> data;

I see a 'const'.

[snip]
std::set<std::string>::iterator it;
for (it = data.begin(); it != data.end(); it++) {

I don't see a 'const' here.

Just lose 'const' in the definition of 'data'.

PS.: Next time think about including a description of what exactly does not work as expected, possibly including compiler error messages.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top