extracting data from std::set<string>

Discussion in 'C++' started by Rene Ivon Shamberger, Oct 19, 2012.

  1. 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;
    }
    Rene Ivon Shamberger, Oct 19, 2012
    #1
    1. Advertising

  2. Rene Ivon Shamberger

    Rui Maciel Guest

    Rene Ivon Shamberger wrote:

    > 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
    Rui Maciel, Oct 19, 2012
    #2
    1. Advertising

  3. Rene Ivon Shamberger

    SG Guest

    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.
    SG, Oct 19, 2012
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page