2013-07-26 82 views
0

兩個大小不均加入載體詞放在一起的功能。如果我有這兩個向量:試圖創建將字符串

vec1: "hello", "world" 
vec2: "it", "is", "sunny", "today" 

resultvector: "helloit", "worldis" 

我需要使用STL這一點,和函子。到目前爲止,我拋出了一個stackdump錯誤:

我的函子: 讀入兩個std字符串,並將它們「+」在一起,返回操作結果。

我的功能:

創建std::list列表,並使用std::transform(vec1.begin(), vec1.end(), vec2.begin(), list.begin(), functor()); return list;

我懷疑的是,我不知道如何使它只重複直到小容器的結束,也可能是我用list.begin()做一些奇怪的事情,並且需要別的東西。

關於如何完成此任務的任何想法?

注:兩個向量std::vector<string>和結果是std::list<string>

預先感謝您的幫助!

+1

發佈您的代碼! – Kevin

+0

謝謝列昂尼德·沃爾尼茨基,它修復了一切 – user2624236

+0

缺乏最基本的理解。 – lpapp

回答

0
#include<iostream> 
#include<algorithm> 

using namespace std; 

struct ff 
{ 
string operator()(const string& x, const string& y){ 
return x+y; } 
}; 

int main() 
{ 
vector <string> vec1{"hello", "world"}; 
vector <string> vec2{ "it", "is", "sunny", "today"}; 
vector <string> resultvector; 
std::transform(
    vec1.begin(), vec1.begin()+min(vec1.size(),vec2.size()), 
    vec2.begin(), 
    back_inserter(resultvector), 
    ff() 
    ); 

for(auto i:resultvector) 
    cout<<i<<endl; 
} 
1

在你的transform調用中,使用back_inserter(list)代替list.begin()back_inserter產生一個迭代器,將分配轉換爲底層容器上的push_back調用。

1
std::transform(
    vec1.begin(), 
    vec1.begin()+std::min(vec1.size(),vec2.size()), 
    vec2.begin(), 
    std::back_inserter(list), 
    functor() 
); 
+0

謝謝,它現在可行! – user2624236

+0

不客氣。順便說一句,使用STD(列表)使用的名稱,不建議。 –