c++ - 如何在 C++ 中创建具有不同行大小的向量?
问题描述
例如,如果我从用户那里获取 n=9 输入。输入为 = {2 3 1 1 2 5 2 7 8} 我的向量应如下所示:-
2 3 1 1 2
2 7 8
即,具有 2 行不同编号的向量。行中的元素。我想跳过将 5 添加到我的向量中。如何才能做到这一点?理想情况下,它不应该有任何空行。即使出现两个连续的 5,或者序列以 5 开始或结束,也不应该有空行。
解决方案
这里有两个解决方案。
第一个检查 5 并在满足某些条件时添加一行以确定是否要添加新行。
如果找到 5,则第二种解决方案添加一行,并在处理循环结束时擦除所有空白行。
解决方案1:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> test = {2, 5, 5, 5, 5, 3, 1, 1, 2, 5, 2, 7, 8};
// Always add an initial first row
std::vector<std::vector<int>> v2d(1);
for (auto v : test )
{
if ( v != 5 )
v2d.back().push_back(v); // add value to the current last row
else
{
// the value is a 5. Check if we need to skip adding this row
if ( !v2d.back().empty() )
// add a new blank row
v2d.push_back({});
}
}
// if last row is blank, remove it.
if ( v2d.back().empty() )
v2d.pop_back();
// output results
std::cout << "The number of rows is " << v2d.size() << "\n";
for ( auto& v1 : v2d )
{
for (auto v : v1 )
std::cout << v << " ";
std::cout << "\n";
}
}
输出:
The number of rows is 3
2
3 1 1 2
2 7 8
解决方案2:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> test = {2, 5, 5, 5, 5, 3, 1, 1, 2, 5, 2, 7, 8};
std::vector<std::vector<int>> v2d(1);
for (auto v : test )
{
// Add a new row if it is a 5
if ( v == 5 )
v2d.push_back({});
else
v2d.back().push_back(v); // add to current last row
}
// remove all the blank rows
v2d.erase(std::remove_if(v2d.begin(), v2d.end(), [&](const std::vector<int>& v) { return v.empty(); }), v2d.end());
// output results
std::cout << "The number of rows is " << v2d.size() << "\n";
for ( auto& v1 : v2d )
{
for (auto v : v1 )
std::cout << v << " ";
std::cout << "\n";
}
}
输出:
The number of rows is 3
2
3 1 1 2
2 7 8
推荐阅读
- java - 当我在 nssm 的帮助下将 jar 作为服务运行时,JOptionPane.showOptionDialog() 没有出现
- sql - 如何减去两个日期时间值?
- ruby - 使用 kubeclient ruby gem 的 K8s API 请求返回错误请求 (400)
- mongodb - 无法通过学说连接mongodb
- reactjs - 防止反应应用在测试时发出实际请求
- android - 升级 okhttp 后出现 BootstrapMethodError
- react-native - Hash Tag '#' 未显示在拨号盘 react-native(电话号码)中
- android - Android - 如何允许点击 alertdialog 后面的项目?
- java - 如何处理不带或不带查询参数的请求
- mysql - 您可以使用 TEXT 数据类型创建表字段吗