0

Ex:

vector<string> myVec = {apple, banana, grape}

How can I print these elements as an ordered list using a range-based loop

Output:

1 apple 
2 banana
3 grape
AndyG
  • 39,700
  • 8
  • 109
  • 143
  • What have you tried so far? Would you mind showing us some code? – lubgr Sep 15 '20 at 19:39
  • 1
    Does this answer your question? [Access index in range-for loop](https://stackoverflow.com/questions/12397532/access-index-in-range-for-loop) – scohe001 Sep 15 '20 at 19:39
  • when you say ordered list, do you mean to sort it, or keep the order? – Jeffrey Sep 15 '20 at 19:44
  • Duplicate is correct in the general sense, but there are work-arounds for the case of `vector` and `array`. Te answers below won't work for any other containers due to lack of contiguous storage. – user4581301 Sep 15 '20 at 20:21

5 Answers5

2

A variation of Jeffrey's answer, but without additional variable:

for (const auto& s : myVec)
{
  std::cout << &s - &myVec[0] << " " << s << "\n";
}

This, of course, prints a "correct" 0-based index. Feel free to add 1 to it :)

Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27
1

Using boost ranges really simplifies things Live Demo

using namespace boost::adaptors;

std::vector<std::string> myVec = {"apple", "banana", "grape"};

for (const auto& element : myVec | indexed(1))
{
    std::cout << element.index() << " " << element.value() << "\n";
}

Produces

1 apple
2 banana
3 grape
AndyG
  • 39,700
  • 8
  • 109
  • 143
0

You are looking for

    size_t position = 1;
    for(const auto& s: myVec)
    {
        std::cout << position << " " << s << "\n";
        position++;
    }

as in

#include <iostream>
#include <string>
#include <vector>

using std::vector;
using std::string;

vector<string> myVec = {"apple", "banana", "grape"};

int main()
{
    size_t position = 1;
    for(const auto& s: myVec)
    {
        std::cout << position << " " << s << "\n";
        position++;
    }
}
Jeffrey
  • 11,063
  • 1
  • 21
  • 42
  • 1
    Yeah, I assumed OP was asking about, well, the range-based part as stated. It would be trivial to add the position. – Jeffrey Sep 15 '20 at 19:41
0

With range-v3, you could write:

for (auto [i, val] : myVec | ranges::views::enumerate) 
{
  std::cout << i << ' ' << val << "\n";
}

Here's a demo.

cigien
  • 57,834
  • 11
  • 73
  • 112
0

This would be a good issue for the original for loop:

const size_t quantity = myVec.size();
for (unsigned int i = 0; i < quantity; ++i)
{
  cout << (i + 1) << "    " << myVec[i] << "\n";
}

Simple, effective. Don't knock the old stuff. :-)

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154