nakiya - 3 months ago 21

C++ Question

Is there a more straight-forward way to do this?

`for_each(v_Numbers.begin(), v_Numbers.end(), bind1st(operator<<, cout));`

Without an explicit

`for`

EDIT:

How to do this for

`std::cin`

`std::vector`

`n`

Answer

You could achieve this using `std::copy`

into a `std::ostream_iterator`

:

```
std::vector<int> v_Numbers; // suppose this is the type
// put numbers in
std::copy(v_Numbers.begin(), v_Numbers.end(),
std::ostream_iterator<int>(cout));
```

It would be even nicer if you add some suffix:

```
std::copy(v_Numbers.begin(), v_Numbers.end(),
std::ostream_iterator<int>(cout, "\n"));
```

This assumes that your container is a `vector<int>`

, so you will have to replace that part with the appropriate type.

**Edit** regarding reading input:

Conversely, you can copy from a range of `std::istream_iterator`

into a `vector`

using `std::back_inserter`

:

```
std::vector<int> v_Numbers;
std::copy(std::istream_iterator<int>(cin), std::istream_iterator<int>(),
std::back_inserter(v_Numbers));
```

If you want to read n elements only, look at this question.