c++ - 从现有数组初始化 vector

标签 c++ vector

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/

相关文章:

java - vector 中的 vector ... Java

c++ - std::vector 的第二个参数

c++ - std::vector 赋值 SIGNAL 11 和 SIGNAL 6

c++ - 修改通过std::future的lambda中的引用捕获的值

c++ - 使用 C++ 在 iOS 中创建目录/文件

c++ - 给定一个整数 K 和一个大小为 t x t 的矩阵。构造一个由前 t 个小写英文字母组成的字符串 s,使得 s 的总成本为 K

c++ - (C++) 访问 vector 对第一列中第一个元素的第一个字符

c++ - 套接字上的音频 C++

c++ - 尝试制作 AMF3 数据包

c++ - boost::math::erf的算法