Home Articles

我可以在c中正确设置运算符[]的std :: vector的第n个值吗?

Asked
Viewed 1337 times
0

我正在学习st的cd :: vector . 我对std :: vector的operator []有两个麻烦 .

假设我通过operator []设置std :: vecotr的第n个值,

(1)第n个值之前的元素未初始化 .

(2)我可以通过operator []设置第n个值,但它不会正确地改变它的大小和迭代器 .

以下是测试代码 .

/* Test class : its has only id_ and it can print it. */
class Tmp {
public :
    Tmp(int new_id) : id_(new_id) {
        std::cout << "class Tmp constructor. id = " << id_ << std::endl;
    }
    void print(void) {
        std::cout << "id = " << id_ << std::endl;
    }
private :
    int id_ = 777;
};

std::vector<Tmp> b;

b.reserve(1);

/* push_back() automatically expands buffer of std::vector. */
b.push_back(Tmp(1));
b.push_back(Tmp(2));
b.push_back(Tmp(3));
b.push_back(Tmp(4));
b.push_back(Tmp(5));

std::cout << "Before operator[] : size = " << b.size() << ", capacity = " << b.capacity() << std::endl;

/* I set the 7 th value. */ 
b[6] = Tmp(7);
b[6].print();

/* Operator[6] does not change size of std::vector. */ 
std::cout << "Before operator[] : size = " << b.size() << ", capacity = " << b.capacity() << std::endl;

 /* Operator[6] did not expand iterator of std::vector correctly. */ 
for (auto it = b.begin(); it != b.end(); ++it) {
    it->print();
}

其产出如下,

class Tmp constructor. id = 1
class Tmp constructor. id = 2
class Tmp constructor. id = 3
class Tmp constructor. id = 4
class Tmp constructor. id = 5
Before operator[] : size = 5, capacity = 8
class Tmp constructor. id = 7
id = 7
After operator[] : size = 5, capacity = 8
id = 1
id = 2
id = 3
id = 4
id = 5

我可以通过operator [n]设置std :: vector的第n个值吗?如果我能做到,如何在第n个值之前初始化值?

非常感谢你 .

1 Answer

  • 1

    是的,您可以使用operator []设置第N个值 . 但是,元素必须已经存在(pos <size());与一些稀疏数据结构(或std :: map)不同,使用vector,operator []不会添加元素 .

    元素通常添加了push_back,insert或resize(还有assign,emplace,emplace_back ......) . 使用resize,有一个可选的第二个参数,用于指定添加元素的初始值 .

    举个例子,您可以:

    std::vector<Tmp> b;
    b.resize(7, Tmp(-1));
    b[6] = Tmp(6);
    

    元素0-5现在包含带有_id == -1的Tmp实例 .

    还有一个类似的构造函数,这段代码完成了同样的事情:

    std::vector<Tmp> b(7, Tmp(-1));
    

    std :: vector :: reserve不会改变容器的大小,它只预先分配一个足够大的内部数组,以便在该容量内添加元素不需要向量重新分配 .

Related