检查元素是否存在于二维矢量中

Check whether an element exists in a 2D vector

本文关键字:于二维 存在 元素 是否 检查      更新时间:2023-10-16

我在 2D 向量中插入了一些元素,并想知道给定元素是否存在于 2D 向量中的任何地方。有没有快速的方法可以找到元素的存在?

向量声明为:vector < vector< int > > v;

如果您没有关于 2D 矢量的更多信息(例如以某种方式排序),那么最好的方法是迭代 2D 矢量的每一行并使用find方法来检查它是否存在。

您可以执行以下操作:

bool does_exist(const vector< vector<int> >&  v, int item){
vector< vector<int> >::const_iterator row;
for (row = v.begin(); row != v.end(); row++) {
if(find(row->begin(), row->end(), item) != row->end() )
return true;
}
return false;
}

您可以使用以下代码对其进行测试:

#include <iostream>
#include <vector>
using namespace std;
int main(){
int item = 12;
vector < vector <int> > v;
vector <int> v1;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
vector <int> v2;
v2.push_back(4);
v2.push_back(5);
v2.push_back(6);
v.push_back(v1);
v.push_back(v2);
if( does_exist(v, item))
cout << "Item " << item << " exist" << endl;
else 
cout << "Item " << item << " does not exist" << endl;
}

没有我希望的那么优雅。给定一个 int 的 2D 向量:

std::vector<std::vector<int>> foo = {
{{1, 2, 3}},
{{5, 6, 7}},
{{8, 9, 13, 15}}
};

您可以执行此操作以查看是否存在 13

bool found =
find_if(foo.begin(), foo.end(),
[](const std::vector<int>& v) -> bool {
return find(v.begin(), v.end(), 13) != v.end();
}) != foo.end();

TL;博士

使用std::find()。

在C++中,请使用标准模板库 (STL)中的函数(如果已提供)。

阐述

假设您有一个 2D 矢量

std::vector<std::vector<int> > matrix = {
{1,2,3}, 
{4,5,6},
{7,8,9}
};

如果您想迭代上述 2d 矢量中的所有元素。

我建议您使用2diterator

bool element_exist(const vector< vector<int> >&  input, int key){
// 2d vector iterator
vector< vector<int> >::iterator row_it; //iterate over each row(s)
vector<int>::iterator col_it; //iterate over column(s)
for (row_it = input.begin(); row_it != input.end(); row_it++) { // iterate each row(s)
for (col_it = row_it->begin(); row_it != row_it->end(); col_it++) {
if(find(row_it->begin(), row_it->end(), key) != row_it->end())
return true;
}
}
}

并且您可以使用另一个布尔变量来获取函数的返回值key_exist

bool_var = element_exist(matrix, key);

整个程序

#include <vector>
#include <iostream>
using namespace std;
bool element_exist(const vector< vector<int> >&  input, int key){
// 2d vector iterator
vector< vector<int> >::const_iterator row_it; //iterate over each row(s)
vector<int>::const_iterator col_it; //iterate over column(s)
for (row_it = input.begin(); row_it != input.end(); row_it++) { // iterate each row(s)
for (col_it = row_it->begin(); row_it != row_it->end(); col_it++) {
if(find(row_it->begin(), row_it->end(), key) != row_it->end())
return true;
}
}
}
int main() {
// declaration
bool bool_var = false; // default false
std::vector<std::vector<int> > matrix = {{1,2,3}, {4,5,6},{7,8,9}};
bool_var = element_exist(matrix,1);
cout << "bool_var: " << bool_var << endl;
return 0;
}

结果

bool_var: 1