c++ - 检查二维 vector 中是否存在元素

标签 c++ vector stl

我在二维 vector 中插入了一些元素,想知道给定元素是否存在于二维 vector 中的任何位置。有什么快速的方法可以找到元素的存在吗?

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

最佳答案

如果您没有关于 2D vector 的更多信息(比如以某种方式排序),那么最好的方法是遍历 2D vector 的每一行并使用 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;
}

关于c++ - 检查二维 vector 中是否存在元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50203818/

相关文章:

c++ - 如何将 std::chrono::system_clock::duration 转换为 struct timeval

c++ - 如何将 std::string 与采用 char[] 缓冲区的 Win32 函数混合?

c++ - 推荐哪本STL引用书?

c++ - 我如何找出 std::istream 中有多少字节可用?

c++ - 为什么 C++ 中的数组在 C++11 之前没有成员函数 size()?

c++ - strstr 总是返回 null

c++ - 批量导入包含在 Eclipse for Opencv 中

r - 如何合并2个向量交替索引?

c++ - 我可以为迭代器赋值吗?

c++ - 使用 Cilk 数组表示法和 STL vector