Transform applied to associative container

1
2
3
4
5
6
7
int main() {
    set<int > sset;
    sset.insert(5);

    transform(sset.begin(), sset.end(), sset.begin(), negate<int>() );

}


Code snippet from C++ Standard Library text. This works with sequential containers, why not with associative? I don't see anything contrary in API.. Is iterator to associative container not in the OutputIterator category?
Last edited on
std::set iterators provide only const access to elements.
The reason is simple: they keep their elements in a sorted tree, so changing the value of an element requires the tree to be updated. "Changing" a value must be done via erase + insert.
As an aside, sets are not associative. Your idea will work on a map.
helios: I think you are wrong. See http://www.cplusplus.com/reference/stl/set/ . Perhaps you intended associative in a different way.
Athar: Thank you

How could I know this from the API though. I can see that the set iterator is not an output iterator. But consider following,

1
2
3
4
5
6
7
8
int main() {
    set<int > sset;
    for(int i = 0; i < 10; i++){
        sset.push_back(i);

    }
    sset.erase(remove_if(sset.begin(), sset.end(), bind2nd(less<int>(), 5)));
}


remove_if requires only a ForwardIterator, which by API, is not required to be able to change values. Yet it still fails.
Last edited on
I ran into this very issue with set last week - apparently, by design (of stl set), the object is the key

that means I can't provide a special operator<() to work with one part of the object and use mutable to allow changes to another part - results in a big const-mess without any benefits

especially since stl set doesn't allow for modification without an erase + insert
Last edited on
See http://www.cplusplus.com/reference/stl/set/ . Perhaps you intended associative in a different way.
Unless a set is a typedef for std::map<T,T>, that definition is wrong.
An associative container stores a relationship between keys and values (e.g. one key to one value, one key to many values, etc.). A set stores "the knowledge of having previously seen a value", so to speak. You can't use a set to, say, store the value of a variable in an interpreted language.
@ helios

I, too, originally took the meaning of associative to mean storing a relationship between key and value - to associate a key to a value.

However, this strange use of associative container to mean anything that is based on a key appears to be standard - I wonder if it has always been like this, or if it was due to stl's use of this term which bastardized its meaning.

http://www.sgi.com/tech/stl/set.html
http://www.sgi.com/tech/stl/AssociativeContainer.html
http://www.sgi.com/tech/stl/SimpleAssociativeContainer.html
Might be STL terminology.
Topic archived. No new replies allowed.