重新组织矢量的内容

Reorganize the content of a vector

本文关键字:新组织      更新时间:2023-10-16

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

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

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

在我的项目上逐步调试 VC++ 并不能帮助我解决问题。在我看来,这个问题很容易解决...

在我看来,这个错误是愚蠢的,但我一直在寻找它很长一段时间。

简单是一种美德,不要把事情复杂化。

这是一个天真的示例,您只需迭代每个标记,然后将其附加到向量的第一个字符串中。特殊情况是第一个和最后一个标记,其中您应该分别只附加一个空格和标记:

#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">

在这种情况下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;
}