簡體   English   中英

C++中的變長數組/數據結構

[英]Variable length array/ data structure in C++

我想在C++實現一個類似於這個的算法,它在MATLAB

A = [1 3 4 2 5 7 8 6];

N = length(A);

v_arr = []

for i=1:1:N
    if somefunction(A(i))
            v_arr =[ v_arr ,i];
    else someOtherfunction(A(i))
            v_arr =[ v_arr ,i];
    end
 end

基本上我想收集滿足某些條件的數組A的索引。 在循環中處理時,在C++存儲這些索引的最有效方法是什么,如上面示例中的v_arr

請在下面找到 CPP 中的 1 對 1 解決方案。

請注意:我想沒有人會像在 C++ 中那樣做。 很可能會使用其他語言結構。

請參見:

#include <iostream>
#include <vector>

// Example function 1. Even numbers
bool someFunction(const int i) {
    return (i%2 == 0);
}

// Exampel function 2. Dividable by 3
bool someOtherFunction(const int i) {
    return (i%3 == 0);
}

int main() {

    // Define Vector and initialize some values
    std::vector<int> A = {1, 3, 4, 2, 5, 7, 8, 6};

    // Get size of vector.The number of elements int he vector
    const size_t N = A.size();

    // Define next dynamic vector (initially empty) for indices
    std::vector<size_t> v_arr{};

    // Loop over all elements from initial data vector
    for (size_t i=0U; i<N; ++i) {

        // Check, if condition 1 is fullfilled
        if (someFunction(A[i])) {

            // Add index to destination  vector
            v_arr.push_back(i);
        }
        // Check, if condition 2 is fullfilled
        else if (someOtherFunction(A[i])) {
            // Add index to destination  vector
            v_arr.push_back(i);
        }
    }
    // SHow result
    for (const int index : v_arr) std::cout << index << " ";
    std::cout <<"\n\n"  ;

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM