const int NUMB = 4;
int n[] = {5,6,7,8};
// create a vector of strings using the n[] array
vector<int> partnums(n, n + NUMB);
类函数vector name(src.begin, src.end)
Create a vector initialized with elements from a source container beginning at src.begin and ending at scr.end
根据书,
The vector partnums is declared as a vector type int and initialized with elements from the n array, starting with the first array element n[0], and ending with the last array element, located at position n + NUMB.
我还是不明白。 “位于n+NUMB位置,索引不是从0开始的吗? 或者编译器知道这个 src.end 指的是位置 1(scr.begin),并从数组 n 中的那个位置开始计数,并计数到第 4 个位置)?
谢谢
最佳答案
C++ 标准库使用一种约定,即“结束”迭代器实际上指的是结束后的一个元素,因此在您的情况下,“开始”将是第 0 个位置,“结束”是第四个(不是第三个)位置。
您在上面的引用中令人困惑的是 n + NUMB
被称为数组中的最后一个元素,这是不正确的。它是数组中最后一个元素之后的(虚构)元素,仅用作结束标记。
关于c++ - 从现有数组初始化 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3527342/