在下面的代碼中,我定義了int的映射和類A的對象。我定義了兩個函數funwithPointer和funwithoutPointer。正如你所看到的,我試圖在類的對象中增加投票並將其添加到地圖中。如果我使用對象的指針,那麼在第三次調用時,我會在沒有指針(funwithoutPointer)的情況下聲明對象時得到2票,無論我多少次調用該函數,我都不能將投票增加到1以上。有什麼問題 ?指向對象的指針混亂
#include<iostream>
#include<map>
using namespace std;
class A{
public:
int x;int vote;
A(int a):x(a),vote(0){}
void change(){
cout<<vote<<endl;
vote++;}
};
void funwithPointer(map<int,A>& m){
for(int i=0;i<5;i++){
if(m.find(i)==m.end()){
A* a=new A(10);
a->change();
m.insert(pair<int,A>(i,*a));
}
else{
A* a=&m.find(i)->second;
a->change();
}
}
}
void funwithoutPointer(map<int,A>& m){
for(int i=0;i<5;i++){
if(m.find(i)==m.end()){
A a= A(10);
a.change();
m.insert(pair<int,A>(i,a));
}
else{
A a=m.find(i)->second;
a.change();
}
}
}
int main(){
map<int,A> m;
funwithoutPointer(m);
funwithoutPointer(m);
funwithoutPointer(m);
}
更快的是使用'lower_bound'而不是'find',那麼如果結果與'end()'相同或者鍵是不同於'我',那麼d o暗示插入。 :-) –
因此:'auto f(map.find(i)); if(f == map.end()|| f-> first!= i)m.insert(f,std :: make_pair(...));否則......' –
@Slava如果我使用m,插入(對(i,a));再次調用change()函數後。那就是我插入a的更新版本。 –
user3747190