简体   繁体   中英

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 .

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 (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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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