重新组织矢量的内容
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;
}
相关文章:
- 使用新行和不使用新行读取文件
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 遇到新行时,有没有办法停止istream_iterator
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- 模板元编程:如何将参数包组合成新的参数包
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 如何使用CLion在Mac上创建一个新的.txt文件
- 错误-我无法在VS2019中打开新的Qt项目
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 为什么新的随机库比std::rand()更好
- 在cygwin中测试新的boost安装时出现cpp错误
- C++:继续创建新的变量可以吗
- Qt:当QListView获得新条目时,如何更新QStringList
- 为C++03编译器编写部分unique_ptr,该编译器与较新的编译器在公共代码库上运行
- c++20[[no.unique_address]]中的新功能是什么
- 将指针类分配给新类,C++
- 如何使用新运算符跟踪在循环中创建的 QLabel
- 如何组织 git 工作流以修复错误并同时引入新功能