重新组织向量的内容

问题描述 投票:2回答:2

我想重新组织一个向量的内容,例如:

// 'v' is the vector

v[0]: "name: "
v[1]: &
v[2]: "James"
v[3]: &
v[4]: 10
v[5]: &
v[6]: "last name: "
v[7]: &
v[8]: "Smith"

并得到这个:

v[0]: "name: " & "James" & 10 & "last name: " & "Smith"

这个例子非常基础。

我试过这样的事情:

std::vector<std::string> organize(std::vector<std::string> tokens) {
        using namespace std;
        vector<string> ret;
        string tmp;
        // The IsString function checks whether a string is enclosed in quotation marks.
        // The s_remove_space function removes spaces from a character string.
        for (string str : tokens) {
            if (IsString(str) || str == tokens[tokens.size() - 1]) {
                ret.push_back(tmp);
                ret.push_back(str);
                tmp.clear();
            }
            else if (s_remove_space(str) != "")
                tmp += str;
        }
        return ret;
    }

如果我们从上面举例说明,输出与输入相同。此外,我的做事方式似乎很残酷。我想使用RegEx系统实现起来非常简单,但我不能/不想使用它们。

在我的项目上逐步调试VC ++并没有帮助我解决问题。这对我来说似乎很容易解决......

在我看来,这个错误很愚蠢,但我一直在寻找它。

c++ string vector
2个回答
1
投票

简单是一种美德,不要过于复杂。

这是一个简单的例子,你只需迭代每个标记,然后将它附加到向量的第一个字符串。特殊情况是第一个和最后一个令牌,在这里你应该只添加一个空格,只包括令牌:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main() {
    vector<string> v = {"\"name: \"", "&", "\"James: \"", "&", "10", "&", "\"last name: \"", "&", "\"Smith\""};
    for(unsigned int i = 0; i < v.size(); ++i) {
        if(i == 0)
            v[0] += " ";
        else if(i == v.size() - 1)
            v[0] += v[i];
        else
            v[0] += v[i] + " ";
    }
    cout << "v[0]: " << v[0] << endl;
}

输出:

v [0]:“name:”&“James:”&10&“last name:”&“Smith”


1
投票

在这种情况下,std::stringstream对于收集结果字符串更有用。

此外,如果您不需要定位,可以使用范围for

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <numeric>

std::vector< std::string >& organize( std::vector< std::string >& v )
{
    std::stringstream result;
    //bool is_first = true;
    //char seperator = ' ';

    for ( const auto& str : v )
    {
        //if (is_first)
        //    is_first = false;
        //else
        //    result << seperator;

        result << str;
    }

    v[ 0 ] = result.str();

    return v;
}

int main()
{
    std::vector< std::string > v = {
          "\"name: \"", "&", "\"James: \"", "&", "10", "&", "\"last name: \"", "&", "\"Smith\""};

    organize( v );

    std::cout << "v[0]: " << v[ 0 ] << std::endl;
}
© www.soinside.com 2019 - 2024. All rights reserved.