0

I've got two vectors, and I want to fill both of them from the cin. My normal approach here is to create two for loops, but today I've tried to do it like this:

vector<long long> a(n);
vector<long long> b(n);

for(auto& vec : {a, b}) {
    for(int i = 0; i < n; ++i) {
        cin >> vec[i];
    }
}

With this solution I get a compilation error, telling me that my vec[i] is a vector, while I expect it to be a long long int:

error: no match for ‘operator>>’ (operand types are ‘std::istream’ {aka ‘std::basic_istream<char>’} and ‘std::vector<long long int>’)

I thought that it is some magic which I can't understand and tried to dereference vec, but that didn't help either:

error: no match for ‘operator*’ (operand type is ‘const std::vector<long long int>’)
   17 |             cin >> (*vec)[i];
      |                     ^~~~

What am I doing wrong here? Why isn't auto& giving me a pointer, as I expect? How do I make this code work?

keddad
  • 1,398
  • 3
  • 14
  • 35
  • 1
    fwiw also in `for (auto& x : a) {..}` there is no pointer, `x` is a reference to elements in `a` – 463035818_is_not_an_ai Jul 14 '20 at 14:14
  • Why do you expect `auto&` to give you a pointer? – NotAProgrammer Jul 14 '20 at 14:17
  • @idclev463035818 sure, but since I'm iterating over `{a, b}`, I expect it to give me references for vectors `a` and `b`. – keddad Jul 14 '20 at 14:17
  • @NotAProgrammer well, & operator [should](https://stackoverflow.com/questions/1943276/what-does-do-in-a-c-declaration) return a pointer to an object (auto, vector in my case), as far as I know – keddad Jul 14 '20 at 14:18
  • There is no `operator&` in your code, you declare a variable of type `auto&` - that is something different – UnholySheep Jul 14 '20 at 14:20
  • Interesting. From the message I get with this code, it looks like a `const` issue: `error: no match for 'operator>>' (operand types are 'std::istream {aka std::basic_istream}' and 'const value_type {aka const long long int}')` – Fred Larson Jul 14 '20 at 14:21
  • I don't know what code you compiled, but your first example (after all *unrelated* issues are fixed manually, post a [mre] when you ask, please) contains an error about `cin` and `const long long int` http://coliru.stacked-crooked.com/a/0a7b4077579a949f – StoryTeller - Unslander Monica Jul 14 '20 at 14:23
  • 1
    Yes you get a reference. In your code you have `cin >> vec[i];`, which is right, but the error message refers to `cin >> (*vec)[i];` which is wrong. The code you show is not the code you've compiled. – Lukas-T Jul 14 '20 at 14:24
  • `{a, b}`, in this case, is a `std::initializer_list>` and `std::initializer_list`'s elements are `const`. – Miles Budnek Jul 14 '20 at 14:27
  • 1
    As suggested by somebody out there: this `auto vec : {&a, &b}` with this `cin >> (*vec)[i];` compiles – Alexey S. Larionov Jul 14 '20 at 14:29

0 Answers0