c++ - 创建 vector 时的默认值,C++

标签 c++ vector

考虑以下代码:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    // create a vector with 20 0s
    std::vector<int> arr(20);
    for (int i = 0; i < arr.size(); i++)
        std::cout<<arr[i];
    return 0;
}

上面的代码创建了一个 vector 20 0的并打印每一个。如果我将构造函数更改为 arr (20,1)它创建了一个 vector 20 1

如果我定义一个类:

class Rectangle {
    int width, height;
  public:
    Rectangle (int,int);
    int area () {return (width*height);}
};

Rectangle::Rectangle (int a, int b) {
  width = a;
  height = b;
}

并创建一个 vector Rectangle s 而不是 int小号:

int main() {
    // create a vector with 20 integer elements
    std::vector<Rectangle> arr(20, Rectangle(2,2));
    for (int i = 0; i < arr.size(); i++)
        std::cout<<arr[i].area();
    return 0;
}

二十4打印出来。但是,当我尝试时:

std::vector<Rectangle> arr(20);

我得到:

prog.cpp: In constructor 'std::vector<_Tp, _Alloc>::vector(std::vector<_Tp, _Alloc>::size_type, const value_type&, const allocator_type&) [with _Tp = Rectangle; _Alloc = std::allocator<Rectangle>; std::vector<_Tp, _Alloc>::size_type = unsigned int; std::vector<_Tp, _Alloc>::value_type = Rectangle; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<Rectangle>]':
prog.cpp:19:34: error: no matching function for call to 'Rectangle::Rectangle()'
     std::vector<Rectangle> arr(20);

我是否需要定义一个不带参数的构造函数才能使其工作?通常,当我不为 vector 提供第二个参数时会发生什么当我使用非基本类型时构造函数?

最佳答案

Do I need to define a constructor with no arguments to make this work?

是的,请参阅此链接: http://en.cppreference.com/w/cpp/container/vector/vector .

这里是std::vector的相关构造函数。

explicit vector( size_type count, const T& value = T(), const Allocator& alloc = Allocator());

如果没有第二个参数,则假定为T() via default parameter .
T() 在您的情况下将变为 Rectangle()

当您使用 std::vector 调用原语时,它的行为类似。
粗略地说,它将调用 default-constructor-syntax 原语,例如int(),产生 0。

This ideone demo显示 int()==0

关于c++ - 创建 vector 时的默认值,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42743604/

相关文章:

vector - 如何在openlayers中隐藏矢量特征

c++ - 使用QFuture调用局部类函数

c++ - std::unordered_map::insert与std::unordered_map::operator []

c++ - 使用链表制作模板类

c++ - 我的代码如何在编译时做一件事,而在运行时做另一件事?

C++ 分配 vector 指针

C++通过指针对象键访问 map 元素给出非法操作错误

Java 从文件中读取对象 vector 仅读取 vector 中的第一个对象

c++ - 我应该始终使用带有自己索引的一维 vector ,还是可以使用多维 vector ?

r - 给定一组向量,如何制作新数据集?