Get index of current element in C++ range-based for-loop(在基于 C++ 范围的 for 循环中获取当前元素的索引)
                            本文介绍了在基于 C++ 范围的 for 循环中获取当前元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
                        
                        问题描述
我的代码如下:
std::cin >> str;
for ( char c : str )
    if ( c == 'b' ) vector.push_back(i) //while i is the index of c in str
这可行吗?或者我将不得不使用老式的 for 循环?
Is this doable? Or I will have to go with the old-school for loop?
推荐答案
假设 str 是 std::string 或其他具有连续存储的对象:
Assuming str is a std::string or other object with contiguous storage:
std::cin >> str;
for (char& c : str)
    if (c == 'b') v.push_back(&c - &str[0]);
这篇关于在基于 C++ 范围的 for 循环中获取当前元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:在基于 C++ 范围的 for 循环中获取当前元素的索引
 
				
         
 
            
        基础教程推荐
             猜你喜欢
        
	     - C语言3个整数的数组 1970-01-01
- 迭代std :: bitset中真实位的有效方法? 2022-10-18
- C++多态 1970-01-01
- C语言数组 1970-01-01
- 总计将在节日礼物上花多少钱 1970-01-01
- C++:为什么结构类需要一个虚拟方法才能成为多态? 2022-10-19
- 向量<unique_ptr<A>>使用初始化列表 2022-10-23
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 用指数格式表示浮点数 1970-01-01
- 对 STL 容器的安全并行只读访问 2022-10-25
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
				 
				 
				 
				