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

陌路散爱 提交于 2019-12-08 01:34:21

问题


How 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 ?


回答1:


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?



回答2:


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




回答3:


Following piece of code appends to stream. similary you can add it to vector also.

class CustomAddFeature 
{
    std::ostringstream m_strm;

    public:

      template <class T>     
      CustomAddFeature &operator<<(const T &v)     
      {
          m_strm << v;
          return *this;
      }
};

as it is template so you can use it for other types also.




回答4:


// C++11
#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector<string>& operator << (vector<string>& op, string s) {
   op.push_back(move(s));
   return op;
}

int main(int argc, char** argv) {
    vector<string> v;

    v << "one";
    v << "two";
    v << "three" << "four";

    for (string& s : v) {
        cout << s << "\n";
    }
}


来源:https://stackoverflow.com/questions/8411733/use-operator-to-push-stdstrings-in-a-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!