在基于 C++ 范围的 for 循环中获取当前元素的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15149354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:05:31  来源:igfitidea点击:

Get index of current element in C++ range-based for-loop

c++for-loopc++11iteration

提问by Shane Hsu

My code is as follows:

我的代码如下:

std::cin >> str;
for ( char c : str )
    if ( c == 'b' ) vector.push_back(i) //while i is the index of c in str

Is this doable? Or I will have to go with the old-school for loop?

这是可行的吗?或者我将不得不使用老式的 for 循环?

采纳答案by Benjamin Lindley

Assuming stris a std::stringor other object with contiguous storage:

假设str是一个std::string或其他具有连续存储的对象:

std::cin >> str;
for (char& c : str)
    if (c == 'b') v.push_back(&c - &str[0]);

回答by Daniel Frey

Maybe it's enough to have a variable i?

也许有一个变量就足够了i

unsigned i = 0;
for ( char c : str ) {
  if ( c == 'b' ) vector.push_back(i);
  ++i;
}

That way you don't have to change the range-based loop.

这样您就不必更改基于范围的循环。

回答by Karthik T

The range loop will not give you the index. It is meant to abstract away such concepts, and just let you iterate through the collection.

范围循环不会给你索引。它旨在抽象出这些概念,并让您遍历集合。

回答by Joel

You can use lambdas in c++11:

您可以在 C++11 中使用 lambda:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>

using namespace std;


int main() {
    std::string str;
    std::vector<char> v;
    auto inserter = std::back_insert_iterator<decltype(v)>(v);

    std::cin >> str;
    //If you don't want to read from input
    //str = "aaaaabcdecccccddddbb";

    std::copy_if(str.begin(), str.end(), inserter, [](const char c){return c == 'b';});

    std::copy(v.begin(),v.end(),std::ostream_iterator<char>(std::cout,","));

    std::cout << "Done" << std::endl;

}

回答by Ron Dahlgren

What you are describing is known as an 'each with index' operation in other languages. Doing some quick googling, it seems that other than the 'old-school for loop', you have some rather complicated solutions involving C++0x lambas or possibly some Boost provided gems.

您所描述的在其他语言中被称为“每个都有索引”操作。进行一些快速的谷歌搜索,似乎除了“老式 for 循环”之外,您还有一些相当复杂的解决方案,包括 C++0x lambas 或一些 Boost 提供的 gems。

EDIT: As an example, see this question

编辑:作为一个例子,看到这个问题