修改std :: set中的元素 [英] Modifying elements in std::set
问题描述
我有以下代码-:
int main()
{
set<string> s;
s.insert( "asas" );
s.insert( "abab" );
for ( auto item : s )
{
cout << item << "\n";
reverse( item.begin(), item.end() );
}
cout << "\n";
for ( auto item : s )
{
cout << item << "\n";
}
}
输出-:
abab
asas
abab
asas
reverse()
函数完全不修改集合中的元素.
我怀疑集合中的元素根本无法修改.但是,如果是这种情况,为什么编译器本身不首先给出错误?
The elements of the set are not being modified at all by the reverse()
function.
I suspect that the elements inside a set cannot be modified at all. But, if this is the case, why doesn't the compiler give an error in the first place itself ?
我在Windows 7上使用带有-std=c++14
标志的TDM-GCC 4.9.2.
I am using TDM-GCC 4.9.2 with -std=c++14
flag on Windows 7.
推荐答案
std::set
的元素为const
.如果您想对元素进行突变,则需要进行插入和删除操作,以将容器置于所需的状态.
Elements of a std::set
are const
. If you want to mutate the elements you need to do insertions and removals to put the container in the state you want.
在您的代码示例中:
for (auto item : s)
被翻译成类似以下内容的
gets translated into something like:
for (auto iter = s.begin(); iter != s.end(); ++iter)
{
auto item = *iter; // Copy!
// loop body
}
循环感应变量item
是set
中元素的副本,而不是对set
中实际元素的引用.结果,set
不变.要更改集合,您需要调用set
的成员函数,例如insert
或erase
.
The loop induction variable item
is a copy of the element from the set
, not a reference to the actual element in the set
. As a result, the set
is not changed. To change a set you need to call a member function of set
, e.g. insert
or erase
.
将item
更改为&item
此处无济于事;如果执行此操作,则由于集合中的元素为const,将导致编译时错误,因此无法对它们应用reverse
.
Changing item
to &item
won't help here; if you do this you'll get a compile-time error because the elements of the set are const, so you can't apply reverse
to them.
这篇关于修改std :: set中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!