c++ - 将 vector 地址分配给迭代器

标签 c++ vector

我希望 vector 迭代器指向一个 vector 元素。我有

#include <iostream>
#include <vector>

int main() {
  std::vector<int> vec = {1,2,3,4,5};
  std::vector<int>::iterator it;

  // want "it" to point to the "3" element, so something like
  //   it = &prices[2];
  //   it = &prices.at(2);

}

但是这些尝试都不起作用。我想我需要一些返回迭代器的 vector 函数,而不是地址(?)

最佳答案

neither of these attempts work

确实,您不能从指向容器元素的指针创建容器迭代器。您只能从容器本身获取它们。

I guess I need some vector function that returns an iterator

是的,begin() 返回指向第一个元素的迭代器。增加它以引用您想要的任何元素。对于第三个,

it = vec.begin() + 2;

或者,更一般地说,

it = std::next(std::begin(container), 2);

即使容器不是随机访问的,它也能工作。

关于c++ - 将 vector 地址分配给迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28051291/

相关文章:

c++ - 如何编写返回 const char* 的函数,这是一个修改后的 const char* 参数?

c++ - Makefile: "No rule to make target..."有多个工作目录

c++ - 使用opencv跟踪边界

c++ - 如何用 vector 中的另一个范围替换一个范围?

c++ - std::vector 的问题

c++ - C++ 中的简明列表/vector

C++ 在 Vector 中使用不可赋值的对象

c++ - 如何更改 cv::Mat 中所有像素的值

c++ - 在 C++ 中将代码分解为几个小函数有什么好处?

c++ - C++ 中的 vector : Why i'm getting so much errors for this simple copy & print program?