2011-12-07 12 views
2

operator<<を使用してをvectorにプッシュする方法私は多くを検索しましたが、ストリームの例しか見つかりませんでした。演算子<<を使用してベクトル内のstd :: stringsをプッシュする

class CStringData 
{ 

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

私は、これは 強固なパラメータのためのシンプルな省略記号(のようなvoid AddData(...))為替として使用したいです。

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

これはまったく可能ですか?

+0

なぜ、「演算子<<」は 'ベクトル'に 'string'を押したいのですか? –

+0

@ニコルボラス:非常に便利で便利だと思われるからです。 1行に多くの文字列を挿入することができます! – Nawaz

+1

@Nawaz:これは、それぞれの 'object.push_back()'コールの間に ''; ''を入れて行うことができます。単一の式でそれを行うことはあなたに何も買わない。そして、ストリーム出力のように見えるので、コードはより鈍いものになります。それはまったくそうではありません。 –

答えて

8

あなたはとして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! 

をしかし、その代わりに、それメンバ関数作りのため、私はそれのfriend作るためにあなたをお勧めします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; 
} 

使用方法は以前と同じです!あなたはそれの友達作り、ルールはどのようなものを好むすべき理由、この読み、探求する

:コードの部分に続いて

+0

あなたは私の一日を作った!どうもありがとう。 – howieh

+1

@howieh答えとしてマークしてください! – jv42

+0

できません...私は100の評判を持っていないので、私は待たなければなりません。 – howieh

0

ストリームに追加します。あなたはそれをベクトルに加えることもできます。

class CustomAddFeature 
{ 
    std::ostringstream m_strm; 

    public: 

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

templateですので、他のタイプにも使用できます。

0
// 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"; 
    } 
} 
関連する問題