简体   繁体   English

C ++向量被另一个向量索引

[英]c++ vector indexing by another vector

sry for asking this obviously easy question but I was unable to find the exact answer for my issue and I'm obviously to inexperienced to derive the answer form similar problems... 很想问这个显然很简单的问题,但是我找不到我问题的确切答案,而且我显然没有经验,无法从类似问题中得出答案...

Suppose I have the following situation 假设我有以下情况

#include <vector>

int main() {
    std::cout << "Test" << std::endl;

    int myints1[] = {1, 1 , 0, 0};
    std::vector<int> vec1 (myints1, myints1 + sizeof(myints) / sizeof(int) );
    int myints2[] = {1, 2 , 3, 4};
    std::vector<int> vec2 (myints, myints2 + sizeof(myints2) / sizeof(int) );

    std::vector<int> resultVec;

    // Now as a result I want to get the resultVec as all entries in vec2 
    // where vec1 == 0, resulting in resultVec = [3,4]
    return 0

}

How to select all entries of one vector by the value of another vector? 如何通过另一个向量的值选择一个向量的所有条目?

Just looping on the index should do the trick here. 仅在索引上循环就可以解决问题。 This code assumes that vec2 s size is at least as big as vec1 . 此代码假定vec2的大小至少与vec1一样大。

int main() {
    std::cout << "Test" << std::endl;

    int myints1[] = {1, 1 , 0, 0};
    std::vector<int> vec1 (myints1, myints1 + sizeof(myints) / sizeof(int) );
    int myints2[] = {1, 2 , 3, 4};
    std::vector<int> vec2 (myints, myints2 + sizeof(myints2) / sizeof(int) );

    std::vector<int> resultVec;

    for (unsigned i = 0; i < vec1.size(); ++i) {
        if (!vec1[i]) resultVec.push_back(vec2[i]);
    }
    return 0

}

You can have a loop that increments two iterators. 您可以有一个递增两个迭代器的循环。 Because your collections are the same type you can decalre both in the for, and because they are the same size, you only need to check one. 因为您的集合是相同的类型,所以您可以在for中对它们进行贴花,并且由于它们的大小相同,因此您只需要检查其中一个即可。

for (auto it1 = vec1.begin(), it2 = vec2.begin(); it1 != vec1.end(); ++it1, ++it2) 
{
     // Use *it1 and *it2
}

If you have access to C++17 and boost, you can use a nice ranged-for 如果您可以使用C ++ 17和boost,则可以使用

for (auto & [val1, val2] : boost::combine(vec1, vec2))
{
     // Use val1 and val2
}

Note that you can use {} to initialise vector s, so I wouldn't bother with myints . 请注意,您可以使用{}初始化vector ,因此我不会为myints

std::vector<int> vec1 = {1, 1, 0, 0};
std::vector<int> vec2 = {1, 2, 3, 4};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM