【问题标题】:How to generate a specific iterator in c++如何在 C++ 中生成特定的迭代器
【发布时间】:2019-12-27 08:57:36
【问题描述】:

有没有办法在 c++ 中生成特定的迭代器?
在 c++ 中,我只是发现:

std::string strHello = "Hello World";
std::string::iterator strIt = strHello.begin();
std::string::iterator strIt2 = std::find(strHello.begin(), strHello.end(), 'W');

其中std::find() 将返回一个迭代器,而.begin() 也是迭代器类型。但是如果我想要一个迭代器初始化一个特定的值,比如:

std::string::iterator strIt3 = strHello[3];  // error

我该怎么做?


更新:
std::string::iterator strIt3 = strHello.begin() + 3; // works well

【问题讨论】:

  • std::string 迭代器是 random access iterators,这意味着 strHello.begin() + 3 完全有效。
  • @某程序员老兄 哦,是真的,我不知道为什么我第一次尝试时无效。谢谢。
  • @HuXixi 另一方面,std::string::iterator strIt3 = strHello[3]; 完全无效,因为operator[] 不返回迭代器
  • @HuXixi 如果在您的实际代码中某处使用了const,您可能会遇到错误。 @robthebloke 的回答涵盖了这一点。

标签: c++ iterator


【解决方案1】:

您可以使用std::next以一般方式返回迭代器的第n个后继:

auto it = v.begin();
auto nx = std::next(it, 2);

注意n可以是负数:

auto it = v.end();
auto nx = std::next(it, -2);

【讨论】:

  • 只是好奇这是否可行,auto it1 = it + 2; ? C++ 新手,我是一名 C 程序员,转而使用 C++
  • @Sohil Omer 是的,如果 itrandom access iterators
  • 您能否分享任何有关“随机访问迭代器”的示例,因为字符串是字符流,因此我可以访问任何索引,就像“C”一样
  • 我需要为随机访问迭代器指定吗
  • @SohilOmer See this.
【解决方案2】:
void without_const(std::string& strHello)
{
  std::string::iterator strIt3 = strHello.begin() + 3;
}

void with_const(const std::string& strHello)
{
  std::string::const_iterator strIt3 = strHello.begin() + 3;
}

void with_auto(const std::string& strHello)
{
  auto strIt3 = strHello.begin() + 3;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 2010-12-21
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多