使用数组填充向量

S.R*_*jit 0 c++ arrays vector

我正在使用这篇文章学习如何在 C++ 中使用向量,他们在下面给出了使用数组填充向量的示例。不过语法有点混乱。

#include <iostream>
#include <string>
#include <vector>

int main() {
    // Array of string objects
    std::string arr[] = {
        "first",
        "sec",
        "third",
        "fourth"
    };

    // Vector with a string array
    std::vector < std::string > vecOfStr(arr,arr +sizeof(arr) / sizeof(std::string)); //This line is confusing
    for (std::string str: vecOfStr)
        std::cout << str << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

就我的理解而言,在向量的变量名称之后是向量的大小。我会想象那本来只是简单的,sizeof(arr) / sizeof(std::string)但它是arr,arr +sizeof(arr) / sizeof(std::string). 谁能告诉我为什么?

Gil*_*ils 6

std::vector有多个构造函数可供您选择。构造函数之一确实接收向量的长度。在您的示例中,正在使用不同的构造函数。一个接收两个迭代器。

您向构造函数传递两个指针,std::string其中两个指针用作迭代器。

加法和除法运算符只是指针算术。