the correct use for auto &i range?

#include <iostream>
#include <vector>

class UserData 
{
    std::string status = "Active"; 
 public:
    std::string first_name;
    std::string last_name;
    std::string get_status() //no colon
    {
        return status;
    }
};

int main()
{
  UserData user1;
  user1.first_name = "LaLaLa";
  user1.last_name = "GGGG";
  UserData user2;
  user2.first_name = "HaHaHa";
  user2.last_name = "DDDDD";


  std::vector<UserData> uservec;
  uservec.push_back(UserData());
  for (auto& i : uservec) { std::cout << i << "\t"; };
}

Complier keeps telling me that no operator "<<" matches these operands at line: for (auto& i : uservec) { std::cout << i << "\t"; };. If I create a function and make a for loop, it will be ok, but I don’t know why I can’t usefor (auto& i : uservec) to read the range ofuservec? Anyone can let me know why, please? Thanks in advance!

>Solution :

The compiler tells you already what is missing. Your class does not have an << operator.

So, please add it and all problems are solved.

Example:

#include <iostream>
#include <vector>

class UserData
{
    std::string status = "Active";
public:
    std::string first_name;
    std::string last_name;
    std::string get_status() //no colon
    {
        return status;
    }
    friend std::ostream& operator << (std::ostream& os, const UserData& ud) {
        return os << ud.first_name << ' ' << ud.last_name;
    }

};

int main()
{
    UserData user1;
    user1.first_name = "LaLaLa";
    user1.last_name = "GGGG";
    UserData user2;
    user2.first_name = "HaHaHa";
    user2.last_name = "DDDDD";


    std::vector<UserData> uservec;

    uservec.push_back(user1);
    uservec.push_back(user2);
    for (auto& i : uservec) { std::cout << i << '\n'; };
}

In the for loop auto& i will return a reference to a UserData element in the vector. Means, in the first loop run "i" will be "user1" and in the next loop run "i" will be "user2".

in the output part, you will then have first:

  • std::cout << user1 << '\n'; and then
  • std::cout << user2 << '\n';

At this time the operator << for your UserData will be called, because you tell the compiler to do so.

So, you use the operator << for an output stream std::ostream (in this case std::cout) and "user1" of type UserData. Then the compiler knows that it needs to call this overloaded operator.

Leave a Reply