要糾正你的錯誤變化
output.push_back(string(&input[i].at(j)));
從
output.push_back(string(input[i].at(j)));
基本上
**for (int i=0; i<input.size(); i++) \\vector iteration**
這是一個錯誤的方式迭代。對於容器迭代器應該被用於從一個矢量迭代
下面複製串
#include <iostream>
#include <iterator>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
vector<string> f (vector<string> input)
{
vector<string> output;
copy(input.begin(),input.end(),back_inserter(output));
return output;
}
int main()
{
vector<string> h{"hello"},x;
x=f(h);
copy(x.begin(),x.end(),ostream_iterator<string>(cout," "));
}
輸出
hello Program ended with exit code: 0
但是,爲了回答你(迭代器和STL可以使用copy_if或lambda的使用)您的代碼的問題和解決辦法
以下是修改後的代碼
#include <iostream>
#include <iterator>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
vector<string> f (vector<string> input)
{
vector<string> output;
for (int i=0; i<input.size(); i++)
{
for (int j=0;j<input[i].size(); j++)
{
output.push_back(string(&input[i].at(j)));
}
}
return output;
}
vector<string> fi (vector<string> input)
{
vector<string> output;
copy(input.begin(),input.end(),back_inserter(output));
return output;
}
int main()
{
vector<string> h{"hello"},x,y;
x=fi(h);
y=f(h);
copy(x.begin(),x.end(),ostream_iterator<string>(cout," "));
copy(y.begin(),y.end(),ostream_iterator<string>(cout," "));
}
輸出
hello hello ello llo lo o Program ended with exit code: 0
解決方案編輯
#include <iostream>
#include <iterator>
#include<vector>
#include<string>
#include<algorithm>
#include <numeric>
using namespace std;
template<typename T, typename... Args>
void push_back_vec(std::vector<T>& v, Args&&... args)
{
(v.push_back(args), ...);
}
int main()
{
vector<string>x;
push_back_vec(x, "abc", "cds", "ma");
string a = accumulate(x.begin(), x.end(), string(""));
cout<<a;
}
輸出
abccdsmaProgram ended with exit code: 0
更容易格式後
#include <iostream>
#include <iterator>
#include<vector>
#include<string>
#include<algorithm>
#include <numeric>
using namespace std;
int main()
{
vector<string>x{"abc", "cds", "ma"},a;
a.push_back(accumulate(x.begin(), x.end(), string("")));
copy(a.begin(),a.end(),ostream_iterator<string>(cout," "));
}
使用iterator爲應對 –
@HariomSingh:你能明確說明的一點一點嗎? –
您可以從錯誤消息中看到原因:它們不能從'char'轉換爲'const char *'。 'char'是你的輸入[i] .at(j),通過檢查字符串的構造函數,它不接受'char',但它確實接受'char *'指向的地址,一個數字表示有多少' char'將從該地址獲取。 –