Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use operator << to push std::strings in a vector

Is it possible to use operator<< to push strings into a vector. I searched a lot but only find stream examples.

class CStringData
{
 
    vector< string > myData;
    // ...
    // inline  operator << ... ???
};

I want this to use as a simple elipsis (like void AddData(...) ) exchange for robust parameters.

CStringData abc;
abc << "Hello" << "World";

Is this possible at all ?

like image 496
howieh Avatar asked Apr 27 '26 19:04

howieh


2 Answers

You can define operator<< as:

class CStringData
{
    vector< string > myData;
  public:
    CStringData & operator<<(std::string const &s)
    {
         myData.push_back(s);
         return *this;
    }
};

Now you can write this:

CStringData abc;
abc << "Hello" << "World"; //both string went to myData!

But instead of making it member function, I would suggest you to make it friend of CStringData:

class CStringData
{
    vector< string > myData;

  public:
    friend  CStringData & operator<<(CStringData &wrapper, std::string const &s);
};

//definition!
CStringData & operator<<(CStringData &wrapper, std::string const &s)
{
     wrapper.myData.push_back(s);
     return wrapper;
}

The usage will be same as before!

To explore why should you prefer making it friend and what are the rules, read this:

  • When should I prefer non-member non-friend functions to member functions?
like image 148
Nawaz Avatar answered Apr 29 '26 07:04

Nawaz


You need to use std::vector.push_back() or std::vector.insert() to insert elements inside a vector.

like image 20
Alok Save Avatar answered Apr 29 '26 08:04

Alok Save



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!