简体   繁体   English

如何在C ++中返回foreach循环的值?

[英]How to return the value of foreach loop in c++?

I need to take multiple lines of string and then prepends with spaces. 我需要使用多行字符串,然后加上空格。

I am using boost::split to split the string and assign the value to a vector. 我正在使用boost :: split来拆分字符串并将值分配给向量。 And then inside for-each loop, I add spaces to the vector value. 然后在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;
  }

I should get the return value as below. 我应该得到如下的返回值。 cout result is correct but the return value txt is unable to get. cout结果正确,但是无法获得返回值txt。

      This is a sentence.
      And another sentence

having

  for(string line : results){ txt = pad + line + nl; cout << txt; } return txt; 

the return txt is the last value of pad + line + nl from the loop or an empty string if results is empty 返回txt是循环中pad + line + nl最后一个值,如果结果为空,则为空字符串

Saying

cout result is correct but the return value txt is unable to get. cout结果正确,但是无法获得返回值txt。

probably means you just need to collapse each string and return the result : 可能意味着您只需要折叠每个字符串并返回结果:

string r;

for(string line : results){
  txt = pad + line + nl;
  cout << txt;
  r += txt;
}
return r;

or something similar may be without pad 或类似的东西可能没有垫子

Another way: 其他方式:

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;
}

Your loop: 您的循环:

for(string line : results){
  txt = pad + line + nl;
  cout << txt;
}
return txt;

resets txt on every loop iteration (and you print that iteration's text one at a time). 在每次循环迭代时重置txt (并且您一次打印一次迭代文本 )。 You then only have the final iteration's value remaining after the loop. 这样,循环之后仅剩下最后一次迭代的值。

Instead, append to txt to keep all values. 而是附加txt以保留所有值。 As a consequence you will also need to hoist the cout out of the loop: 因此,你还需要扯起cout跳出循环:

for(string line : results){
  txt += pad + line + nl;
}
cout << txt;
return txt;

I'll show the part of the function where the vector is already built. 我将显示已构建矢量的函数部分。 So the function I'll show is simplified but demonstrates how you can build and return the result string. 因此,我将展示的功能得到了简化,但展示了如何构建和返回结果字符串。

#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 );
}

The program output is 程序输出为

 This is a sentence.
 This is a sentence.

To make the code more effective you should reserve enough space for the string txt . 为了使代码更有效,您应该为字符串txt保留足够的空间。 The loop 循环

    for ( const std::string &s : results ) n += s.length();

calculates the total size of all strings stored in the vector. 计算向量中存储的所有字符串的总大小。

Note: You could use the standard algorithm std::accumulate declared in the header <numeric> instead of the loop as for example 注意:您可以使用标头<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();
                                            } );

Then you add the length of padding spaces for each string and the length of the character '\\n' . 然后,为每个字符串添加填充空格的长度以及字符'\\n'的长度。

Thus all is prepared to build the result string that is returned from the function. 因此,所有人都准备构建从函数返回的结果字符串。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM