简体   繁体   English

使用operator <<在向量中推送std :: strings

[英]use operator << to push std::strings in a vector

How it possible to use operator<< to push string s into a vector . 如何使用operator<<string s推入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. 我想将它用作一个简单的省略号(如void AddData(...) )交换,以获得健壮的参数。

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

Is this possible at all ? 这有可能吗?

You can define operator<< as: 您可以将operator<<定义为:

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 : 但是我建议你把它变成CStringData friend ,而不是让它成为成员函数:

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: 要探索为什么你喜欢把它变成朋友和规则是什么,请阅读:

您需要使用std :: vector.push_back()std :: vector.insert()在向量中插入元素。

// 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";
    }
}

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. 因为它是template所以你也可以将它用于其他类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM