Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有两个输入参数的向量构造函数 我在一个项目中遇到了一个C++代码,它初始化了一个带有两个输入的向量。_C++_Vector_Constructor_Std - Fatal编程技术网

带有两个输入参数的向量构造函数 我在一个项目中遇到了一个C++代码,它初始化了一个带有两个输入的向量。

带有两个输入参数的向量构造函数 我在一个项目中遇到了一个C++代码,它初始化了一个带有两个输入的向量。,c++,vector,constructor,std,C++,Vector,Constructor,Std,其中一个输入是现有数组,另一个输入是相同的数组加上数组长度 我在另一个网站上发现了一段类似的代码: // Create an array of string objects std::string arr[] = {"first", "sec", "third", "fourth"}; // Initialize vector with a string array std::vector<std::string> vecOfStr(arr, arr + sizeof(arr)/s

其中一个输入是现有数组,另一个输入是相同的数组加上数组长度

我在另一个网站上发现了一段类似的代码:

// Create an array of string objects
std::string arr[] = {"first", "sec", "third", "fourth"};

// Initialize vector with a string array
std::vector<std::string> vecOfStr(arr, arr + sizeof(arr)/sizeof(std::string));

for(std::string str : vecOfStr)
    std::cout << str << std::endl;

您需要了解的最重要的事情可能是,
std::string[]
可以隐式转换为
std::string*
(指向数组中第一个元素的指针)

因此,在您的示例中,
arr+sizeof(arr)/sizeof(std::string)
是指向数组末尾的指针(
sizeof(arr)/sizeof(std::string)
给出数组中的元素数)


因此,传递给
vector
构造函数的两个元素是指针,它们可以充当迭代器,并使用
arr
中的四个元素初始化
vector
arr
本身的类型为
std::string[4]
。当传递给函数时,它是指向第一个元素的指针。在表达式
arr+sizeof(arr)/sizeof(std::string)
中,首次出现的
arr
再次衰减。第二个不是
sizeof(arr)/sizeof(std::string)
因此计算结果为
4
,这是数组范围。整个表达式
arr+sizeof(arr)/sizeof(std::string)
然后计算为指向经过
arr
中最后一个元素的位置的指针。这通常称为结束迭代器。这有效地调用了构造函数
向量(首先是InputIterator,最后是InputIterator,…)
其中
InputIterator
是用
std::string*
实例化的:

我在另一个站点上发现了一段类似的代码:--当你使用完该代码后,将该行更改为
std::array={“first”,“sec”,“third”,“第四”};
这样元素的数量就是
arr.size()。
vector (InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type());