我正在尝试了解std :: allocator的工作方式,并尝试完成一个简单的任务。任务是删除例如第二个元素,并在删除元素后将其向左移动。
例如,我们将其作为输入数组:1,2,3,其输出应类似于1,3。我得到的输入是:1,3,3
这件事没有发生,这就是为什么我在这里问你。
但是,当我使用**std::allocator<string> myVar**
而不是**std::allocator<int> myVar**
时,它可以工作。
然后输入:一个,两个,三个,输出为:一个,三个
这里是使用std::allocator<int>
的代码:
#include <iostream>
#include <memory>
using namespace std;
int main()
{
allocator<int> a1;
int* arr = a1.allocate(3);
for (int i = 0; i < 3; i++)
a1.construct(arr + i, i + 1);
a1.destroy(arr + 1);
a1.construct(arr + 1, 3);
for (int i = 0; i < 3; i++)
cout << arr[i] << " ";
cout << endl;
a1.deallocate(arr, 3);
return 0;
}
这是std::allocator<string>
的代码:
#include <iostream>
#include <memory>
#include <string>
using namespace std;
int main()
{
allocator<string> a1;
string* wrd = a1.allocate(3);
a1.construct(wrd, "one");
a1.construct(wrd + 1, "two");
a1.construct(wrd + 2, "three");
a1.destroy(wrd + 1);
cout << wrd[0] << " " << wrd[1] << " " << wrd[2] << endl;
a1.deallocate(wrd, 3);
return 0;
}