簡體   English   中英

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

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

如何使用operator<<string s推入vector 我搜索了很多,但只找到流示例。

class CStringData
{

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

我想將它用作一個簡單的省略號(如void AddData(...) )交換,以獲得健壯的參數。

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

這有可能嗎?

您可以將operator<<定義為:

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

現在你可以這樣寫:

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

但是我建議你把它變成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;
}

用法與以前一樣!

要探索為什么你喜歡把它變成朋友和規則是什么,請閱讀:

您需要使用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";
    }
}

下面一段代碼附加到流。 相似你也可以將它添加到矢量。

class CustomAddFeature 
{
    std::ostringstream m_strm;

    public:

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

因為它是template所以你也可以將它用於其他類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM