C++ 如何在c+中的vector2中查找vector1的索引+;

C++ 如何在c+中的vector2中查找vector1的索引+;,c++,C++,我花了大约一周的时间讨论这个问题,我有两个向量,例如vec1和vec2,我想在搜索后从vec1中找到值,然后在vec2中返回它们的索引,其中只找到了,例如: vector<int>vec2 = { 1, 2, 2, 4 }; vector<int>vec1 = { 1, 2, 4 }; 结果: 密码1: 1 0 0 0 密码2: 0 1 1 0 密码3: 0 0 0 1 最终结果: 0

我花了大约一周的时间讨论这个问题,我有两个向量,例如vec1和vec2,我想在搜索后从vec1中找到值,然后在vec2中返回它们的索引,其中只找到了,例如:

vector<int>vec2 = { 1, 2, 2, 4 };
vector<int>vec1 = { 1, 2, 4 };
结果:

密码1:

1     0     0     0
密码2:

0     1     1     0
密码3:

0     0     0     1
最终结果:

0     0     0     1

我的代码(不编译):

我的代码:

#include <vector>
#include <iostream>
using namespace std;

vector<int> find_index(vector<int>vec2, vector<int>vec1)
{
    std::vector<double> tmp;
    for (int i = 0; i<vec2.size(); i++)
    {
        for (int j = 0; j<vec2.size(); j++)
        {
            if (vec2[i] == vec1[j])
            {
                tmp.push_back(i);
            }
        }
    }
    return tmp;
}

int main()
{
    vector<int>vec2 = { 1, 2, 2, 4 };
    vector<int>vec1 = { 1, 2, 4 };
    cout << find_index(vec2, vec1);
    getchar();
    return 0;
}
#包括
#包括
使用名称空间std;
向量查找索引(vectorvec2,vectorvec1)
{
std::载体tmp;

对于(int i=0;i代码,您无法编译,原因有二:

  • tmp
    向量使用
    double
    项类型。
    vector
    不会隐式转换为所需的函数结果类型
    vector


  • 标准库没有定义向量的输出,所以
    您在本周内是否编写了任何代码?请向我们展示您的尝试。划分et impera。首先尝试查找向量中特定数字的索引(如果有)。std::find是您的朋友。@Satus对于获取索引,我们通常可以这样做(以下代码)但是为了得到我的意思中的索引,我不知道怎么做。
    #include#include使用名称空间std;vector find_index(vectorvec2,vectorvec1){std::vector tmp;for(int i=0;i@Cheers还有hth.-Alf你能给我写个例子吗,我可以找到索引,但我的问题是重复索引谢谢你修改了我的代码,它很有用,但我的问题还没有解决,我不知道如何在每次传递中找到重复索引,并用1替换它们,你知道吗?
    
    #include <vector>
    #include <iostream>
    using namespace std;
    
    vector<int> find_index(vector<int>vec2, vector<int>vec1)
    {
        std::vector<double> tmp;
        for (int i = 0; i<vec2.size(); i++)
        {
            for (int j = 0; j<vec2.size(); j++)
            {
                if (vec2[i] == vec1[j])
                {
                    tmp.push_back(i);
                }
            }
        }
        return tmp;
    }
    
    int main()
    {
        vector<int>vec2 = { 1, 2, 2, 4 };
        vector<int>vec1 = { 1, 2, 4 };
        cout << find_index(vec2, vec1);
        getchar();
        return 0;
    }
    
    void write_to( ostream& stream, vector<int> const& v )
    {
        for( int i = 0; i < int( v.size() ); ++i )
        {
            stream << (i > 0? " " : "") << v[i];
        }
    }
    
    write_to( cout, find_index(vec2, vec1) );
    cout << "\n";
    
    0 1 2 3