以下のプログラムでは、空のストアに文字列が追加されます。次に、このストア要素のアドレスがポインタ 's1'に格納されます。次に別の文字列が追加され、元の要素へのポインタが何らかの理由で失敗します。文字列とストア
#include <iostream>
#include <string>
#include <vector>
class store2
{
public:
void add(std::string s) {words.push_back(s); last_added2 = &words.at(words.size() - 1);}
std::string* last_added() {return last_added2;}
private:
std::string* last_added2;
std::vector<std::string> words;
};
void main()
{
store2 store;
store.add("one");
std::string* s1 = store.last_added();
std::cout<<*s1<<std::endl;
store.add("two");
std::cout<<*s1<<std::endl; // crash
}
これはstd :: vectorである必要はなく、std :: vectorsの多くの能力は必要ありませんが、サイズを変更する必要があり、要素は確実にアドレス可能である必要があります。 – alan2here
ランダムアクセスが必要ない場合は、 'std :: list'を使うことができます – peoro
最近追加されたアイテムをリストにアクセスして個々の要素にアドレスを保持することは可能ですか? – alan2here