2011-12-07 37 views
2

如何使用operator<<string s推入vector。我搜索了很多,但只找到流示例。使用运算符<<将std :: strings推入向量

class CStringData 
{ 

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

我希望这是一个简单的省略号使用(如void AddData(...))换取 强大的参数。

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

这可能吗?

+0

为什么你希望*把operator''push'string's'换成'vector'? –

+0

@NicolBolas:因为它看起来非常有用,而且得心应手。你可以在一行中插入很多字符串! – 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! 

但不是使其成员函数,我会建议你做它的friendCStringData

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"; 
    } 
} 
相关问题