80 questions
12
votes
2
answers
937
views
How can I iterate a flat_map in a range-based 'for' loop, updating values?
It is easy to iterate std::map and update values:
#include <iostream>
#include <map>
int main() {
std::map<int, int> m;
m[1] = 2;
m[2] = 4;
for (auto &[k, v] : m)...
2
votes
2
answers
151
views
Structured binding for std::views::enumerate of std::map [duplicate]
I'm trying to do something like this:
const std::map<char, int> histogram{
{'A', 2},
{'D', 1},
{'M', 1},
};
for (const auto& [index, key, value] : std::views::enumerate(...
6
votes
1
answer
373
views
How does `template for` iteration work in C++26? [duplicate]
I'm experimenting with the new C++ compile-time reflection features (as described in P2996R0) and I testing a simple enum_to_string() utility using template for:
template <typename E>
requires ...
0
votes
3
answers
93
views
C++ - Range based loop and namespaces [duplicate]
I've read that to make one's custom container work with range-based for loop, "things" need to be in the same namespace. What things need to be in same namespace? The begin-end free ...
2
votes
1
answer
150
views
What would happen if I append elements in range based for? [duplicate]
I want to modify (push_back) element while iterate vector like this:
auto main() -> int {
std::vector<double> v { 1, 2, 3 };
for (auto& num : v) {
std::cout << num &...
2
votes
2
answers
116
views
get lines from a ifstream into strings in a range-based for loop
I use to parse lines from a file by writing,
ifstream input(filename);
for (string line; getline(input, line); /**/)
do_something_with(line);
...
but is it possible to elegantly (or with some boost ...
1
vote
1
answer
214
views
C++ Does Ranged-Based For Loop Use RValue Reference? [duplicate]
Hi I have a quick question - over here it says ranged-based for loops of the form
for ( init-statement (optional) range-declaration : range-expression )
are equivalent to the code:
{
auto &&...
0
votes
1
answer
130
views
C++ Qt best way to loop over a vector that is a member of a vector of parent dummy objects also being looped over
I want to loop over a vector of objects each containing another vector of objects to be looped over in turn. The subvector/contained vector object members need to be able to be able to be modified and ...
0
votes
2
answers
173
views
Range of enums in C++
I'm confused with range of enums.
I have code like this:
namespace regs {
enum Control_0 {
THING1,
THING2,
THING3
};
enum Control_1 {
THING100,
THING200,
THING300
};
const auto ...
3
votes
1
answer
140
views
Range-based for loop: why is ordinary lookup not performed?
In range-based for when begin-expr and end-expr are begin(range) and end(range), the names begin and end are not looked up using ordinary lookup. Just ADL is performed. See C++23 [stmt.ranged]#1.3.3.
...
3
votes
2
answers
899
views
Erasing nodes of a std::map within a range-based "for" loop
I need to check data of a std::map, and remove some of them.
I'm using a range-based "for" loop, like this:
std::map<int, string> data { { 1, "name1" }, { 2, "name2"...
3
votes
2
answers
237
views
A c++20 range adaptor whose produced values are iterators to the underlying range
I want to have the following work
std::vector<int> range{0,1,2,3};
for(std::vector<int>::iterator vit : range | iterator_range ){
int v = *vit;
}
this would be equivalent to the ...
0
votes
0
answers
46
views
range - based loop traversal in array [duplicate]
**The code I tried to implement is : **
#include<iostream>
using namespace std;
int main()
{
int n, k;
cout << "Enter the number of elements: \n";
cin >> n;
...
0
votes
1
answer
119
views
Why is iterating over the set and modifying element not allowed here [duplicate]
In the following code, we cannot iterate over set s1 using non-const reference. Why?
#include <set>
struct st {
unsigned int f;
std::set<int> s2;
};
struct comp {
bool operator()(...
0
votes
2
answers
131
views
Usage of std::span with non-iterable type
I was trying out some C++20 when I stumbled upon a rather strange (at least to me) situation. I was expecting the following code to not work with one of my examples (I've specified the expected ...
-2
votes
1
answer
339
views
Iterating over a vector of shared_ptrs in a range-based for loop
I feel like this should have an answer already but I wasn't able to find it.
I have a vector of shared_ptrs:
vector<shared_ptr<X>> v;
I don't want to do anything with ownership (e.g. ...
1
vote
1
answer
115
views
Multi variable range based for loop c++
Can I write a range based for loop in c++ with two parallel iterators
I have code like this -
class Result{
...
...
};
std::vector<Result> results;
std::vector<Result> groundTruth(...
0
votes
0
answers
79
views
How to make "auto" type deduction compatible with range-based "for"?
I am learning to make the self-defined class compatible with the range-based 'for' loop.
Given the range class:
class range
{
private:
range_iterator m_begin;
range_iterator m_end;
public:
...
1
vote
1
answer
1k
views
Structured binding with map in range-based loop captures by reference instead of value
In the code below I use auto (not auto&, const auto, const auto& or auto&&), but k has a reference type.
Why is it captured by reference (as GCC says) and not by value? Looks ...
5
votes
1
answer
148
views
Why doesn't iterate over a container accessed directly through std::optional<T>::value() work?
I'm trying to iterate over a std::vector<X> contained in a struct T that I access through a std::optional<T>. Contrary to my expectations, the behavior is different if I first store the ...
1
vote
2
answers
468
views
Range for loop for empty initializer list
I was reading about forwarding references on cpp reference https://en.cppreference.com/w/cpp/language/reference#Forwarding_references and I was interested to learn that there is a special case for ...
0
votes
1
answer
128
views
Printing 2D array with forEach in C++, but without using auto keyword
I have come across the solution to print the 2 D array using C++.
The ans was to use auto keyword:
for eg:
double nut_torques[4][5]; // this is my array with type double
for (auto& rows : ...
3
votes
1
answer
102
views
What does the auto "t{1U}" do in the following range-based for loop from std::make_heap example?
I was browsing the standard algorithm library and came across an example which used a range based for loop in a way that I had not seen before: https://en.cppreference.com/w/cpp/algorithm/is_heap
In ...
0
votes
0
answers
50
views
Range based for loop in function as reference throws error (C++) [duplicate]
I just learned range based for loops in c++ and i'm trying to create a function that initializes a vector to all 0's; i did the following:
#include <vector>
// #include <algorithm>
// #...
2
votes
2
answers
968
views
How to iterate over a list of smart pointers?
In Herb Sutter's 2014 CppCon talk, he talks about how you shouldn't have smart pointers in your function declaration if you don't intend to transfer or share ownership. And most definitely, no const ...
3
votes
1
answer
582
views
Deleting map elements in a range-based loop
I would like to drop a number of elements from a map based on some condition:
#include <unordered_map>
#include <ranges>
#include <iostream>
int main() {
std::unordered_map<...
-1
votes
1
answer
125
views
Get a random number when emplace an element with range-based for loop
I wrote a program to insert the numbers in C++ with CLion.
First, enter a set of positive integers and place them into the vector called pour.
Then, take the negative numbers of these positive ...
0
votes
1
answer
54
views
How to make a spaced line of strings from a vector in C++
I want to make a line like this hello my name sounds very fancy from a vector of these words (std::vector<std::string> myvector = {"hello", "my", "name", "...
0
votes
1
answer
115
views
r-value lifetime issue (stack-use-after-scope): How to move std::initializer_list
Usage
I have two classes, which give me a counter in range based for loops (bit like a simple ranges v3 lib).
// Usage with l-values
std::initializer_list<int> li = {10, 11, 12, 13, 14};
for (...
-4
votes
1
answer
97
views
What is the difference in using and not using "&" in range-based for loops usually iterating over maps in C++? [duplicate]
for (auto& it: map_name) { // __ some _ code __ }
I want to know whether using & makes any big difference and can we use it to directly access second element of the iterator?
2
votes
0
answers
97
views
Why range based for loop doesn't work with iterator, which points to container? [duplicate]
I have this code and it doesn't compile. It has an error:
cannot assign to variable 'value' with const-qualified type 'const int &'
value = 5;
#include <vector>
#include <set>
int ...
-1
votes
1
answer
68
views
Multidimensional arrays [duplicate]
I was curious about why we go through a multidimensional array this way
for (auto& row : mat1)
{
for (int& elements : row)
{
cin >> elements;
}
...
5
votes
1
answer
631
views
Is there a technical reason why range-based for loop doesn't detect whether it's looping on an rvalue?
The reason for the question is that I've seen code like this:
auto fun(std::vector<Foo>&& v) {
std::vector<Bar> w;
for (auto&& e : v /* not an rvalue, but keep ...
0
votes
1
answer
694
views
how to tell compiler to do "range based for loop" in string vector?
I have created a string vector and want to fill it with a "range-based for loop" but it doesn't work. What am I doing wrong?
invalid initialization of reference of type ‘int&’ from ...
2
votes
1
answer
630
views
range-expression of range based for loop in C++
I am trying to pass a pointer of vector to range based for loop for its range-expression.
Here is the syntax of range based for loop:
attr(optional) for ( init-statement(optional) range-declaration : ...
0
votes
0
answers
49
views
Difference between auto& and auto&& in structured binding used in range-based for loop [duplicate]
(Please let me know if this is a duplicate. I tried to search previous questions but couldn't find the same one.)
When structured binding is used in a range-based for loop like this:
for (auto & [...
1
vote
4
answers
790
views
How can I add up the values of the individual digits in a string?
I want to get the sum of the individual digits of an ID entered by the user. So far this is the code I have, and my code can count the number of characters in the user input but I'd like for it to ...
1
vote
1
answer
59
views
Range based for loop iteration on std::map need for explanation [duplicate]
The following code is running properly
#include<iostream>
#include<map>
#include<algorithm>
#include<string>
#include<vector> using namespace std;
int main() {
std::...
0
votes
2
answers
124
views
C++ Why are my Objects being destroyed, and sometimes twice in a row when using range based for loop [duplicate]
I'm a beginner programmer looking to understand why my objects are being deleted, sometimes even twice. I'm trying to avoid creating them on the heap for this project as that is a more advance topic I ...
0
votes
3
answers
397
views
C++ iterating and range-for-loop differences
I have a chunk of C++ code that is supposed to go through a sorted vector and delete reoccurring objects in-place. I completed the task (C1) using an iterator. I continued with the problem and wanted ...
1
vote
5
answers
851
views
How to add a list to a string? [duplicate]
I am trying to add a list to a string.
int main() {
std::cout << "Hello, welcome to Jay's Coffee!!\n";
std::string name; std::cout <<"What is your name "; std::cin >...
3
votes
1
answer
263
views
Don't print space after last value with iterator
I'm having a problem with a beginner concept
in competitive programming extra space in print may cause wrong answer judgment
I want to iterate through a container like map or set but last value should ...
-1
votes
1
answer
96
views
Why is my range-based for loop working for some data types but not others? [closed]
I tried out some range-based for loops to get an idea of the concept and for arrays and vectors of integers, it works fine. But for a vector of characters, my compiler does not give any error messages ...
2
votes
5
answers
344
views
using remove method of std::list in a loop is creating segmentation fault
I am using remove() of std::list to remove elements in a for loop. But it is creating segmentation fault. I am not using iterators. Program is given below.
#include <iostream>
#include <list&...
4
votes
1
answer
383
views
how to write forward iterator using private std::vector base class
I need a vector class that exposes a small subset of the std::vector API. Everything works except range-based for. Here my attempt at implementing a forward iterator, which however does not compile.
#...
0
votes
1
answer
999
views
How to iterate through a range-based for loop when the data type of the array is const char *?
I am trying to solve the following question:
https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1/train/cpp in C++.
When I try to iterate over a range based for loop I get the following error ->
...
1
vote
1
answer
1k
views
Continue in range based for loop after exception
I have the following program that iterates through a directory and can catch exceptions:
#include <iostream>
#include <filesystem>
#include <exception>
int main() {
const std::...
0
votes
1
answer
624
views
Custom class range based for-loop over a 2D map
I have the following class MyClass that contains a 2D map (std::map<std::string, std::map<std::string,double>>).
I would like to know if it is possible to implement the MyClass::begin() ...
6
votes
1
answer
119
views
What is member interpretation in Range-based for loop (since C++11)?
I read this documentation for a range-based for loop:
The member interpretation is used if the range type has a member named begin and a member named end. This is done regardless of whether the ...
2
votes
3
answers
1k
views
Find element in a vector with previous and next element equal to 0
I want to go through a given vector of integers and find an integer which the value of the next and previous integer are 0.
#include <iostream>
#include <vector>
using namespace std;
int ...