有两个关于替换不可赋值的向量元素的问题:
对象不可分配的典型原因是其类定义包含const成员,因此将其operator=删除.
std::vector要求其元素类型可分配.事实上,至少使用GCC,当对象不可分配时,直接赋值(vec[i] = x;),erase()以及insert()替换元素的组合都不起作用.
可以使用像下面这样的函数来使用vector::data(),直接元素销毁和使用复制构造函数的新元素来替换元素而不会导致未定义的行为吗?
template <typename T>
inline void replace(std::vector<T> &vec, const size_t pos, const T& src)
{
T *p = vec.data() + pos;
p->~T();
new (p) T(src);
}
Run Code Online (Sandbox Code Playgroud)
下面是一个使用函数的例子.这在GCC 4.7中编译并且似乎有效.
struct A
{
const int _i;
A(const int &i):_i(i) {}
};
int main() {
std::vector<A> vec;
A c1(1);
A c2(2);
vec.push_back(c1);
std::cout << vec[0]._i << std::endl;
/* To replace the element …Run Code Online (Sandbox Code Playgroud) 如何将push_back()转换为C++ std :: vector而不使用默认定义违反const成员的operator =()?
struct Item {
Item(int value)
: _value(value) {
}
const char _value;
}
vector<Item> items;
items.push_back(Item(3));
Run Code Online (Sandbox Code Playgroud)
我想保留_value const,因为它在构造对象后不应该改变,所以问题是如何在不调用operator =()的情况下用元素初始化我的向量?
这是g ++ v3.4.6给我的基本错误:
.../3.4.6/bits/vector.tcc: In member function `Item& Item::operator=(const Item&)':
.../3.4.6/bits/vector.tcc:238: instantiated from `void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typename _Alloc::pointer, std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp = Item, _Alloc = std::allocator<Item>]'
.../3.4.6/bits/stl_vector.h:564: instantiated from `void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = Item, _Alloc = std::allocator<Item>]'
item.cpp:170: instantiated from here
.../3.4.6/bits/vector.tcc:238: error: non-static const member `const char Item::_value', can't …Run Code Online (Sandbox Code Playgroud)