[英]How to return the value of foreach loop in c++?
我需要使用多行字符串,然后加上空格。
我正在使用boost :: split來拆分字符串並將值分配給向量。 然后在for-each循環中,我向向量值添加空格。
static string test(){
std::string text = "This is a sentence.\nAnd another sentence";
string nl = "\n";
string pad=" ";
string txt;
std::vector<std::string> results;
boost::split(results, text, boost::is_any_of(nl));
for(string line : results){
txt = pad + line + nl;
cout << txt;
}
return txt;
}
我應該得到如下的返回值。 cout結果正確,但是無法獲得返回值txt。
This is a sentence.
And another sentence
有
for(string line : results){ txt = pad + line + nl; cout << txt; } return txt;
返回txt是循環中pad + line + nl
的最后一個值,如果結果為空,則為空字符串
說
cout結果正確,但是無法獲得返回值txt。
可能意味着您只需要折疊每個字符串並返回結果:
string r;
for(string line : results){
txt = pad + line + nl;
cout << txt;
r += txt;
}
return r;
或類似的東西可能沒有墊子
其他方式:
static string test(){
std::string text = "This is a sentence.\nAnd another sentence\n";
std::string result = " " + boost::algorithm::replace_all_copy(s, "\n", "\n ");
std::cout << result;
return result;
}
您的循環:
for(string line : results){
txt = pad + line + nl;
cout << txt;
}
return txt;
在每次循環迭代時重置txt
(並且您一次打印一次迭代文本 )。 這樣,循環之后僅剩下最后一次迭代的值。
而是附加到txt
以保留所有值。 因此,你還需要扯起cout
跳出循環:
for(string line : results){
txt += pad + line + nl;
}
cout << txt;
return txt;
我將顯示已構建矢量的函數部分。 因此,我將展示的功能得到了簡化,但展示了如何構建和返回結果字符串。
#include <iostream>
#include <string>
#include <vector>
static std::string test( const std::vector<std::string> &results )
{
const std::string pad( " " );
std::string::size_type n = 0;
for ( const std::string &s : results ) n += s.length();
n += results.size() * ( pad.size() + sizeof( '\n' ) );
std::string txt;
txt.reserve( n );
for ( const std::string &s : results ) txt += pad + s + '\n';
return txt;
}
int main()
{
std::vector<std::string> results = { "This is a sentence.", "This is a sentence." };
std::cout << test( results );
}
程序輸出為
This is a sentence.
This is a sentence.
為了使代碼更有效,您應該為字符串txt
保留足夠的空間。 循環
for ( const std::string &s : results ) n += s.length();
計算向量中存儲的所有字符串的總大小。
注意:您可以使用標頭<numeric>
聲明的標准算法std::accumulate
代替循環,例如
std::string::size_type n = std::accumulate( std::begin( results ), std::end( results ),
std::string::size_type( 0 ),
[]( const std::string::size_type acc, const std::string &s )
{
return acc + s.size();
} );
然后,為每個字符串添加填充空格的長度以及字符'\\n'
的長度。
因此,所有人都准備構建從函數返回的結果字符串。
std::string txt;
txt.reserve( n );
for ( const std::string &s : results ) txt += pad + s + '\n';
return txt;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.