簡體   English   中英

在C ++中將子向量作為函數參數傳遞

[英]Passing sub-vector as function argument in c++

給定大小為10的向量v1,我希望將v1的第1,第3和第7個元素作為單個函數參數傳遞。 除了創建另一個向量v2之外,還沒有其他更有效的方法來傳遞參數(即,不創建v2並按值復制元素),而是通過按值復制v1的三個元素並傳遞v2的引用來代替?

取決於期望的行為,可以傳遞一個vector<reference_wrapper>或其他容器reference_wrapper

#include <vector>
#include <functional>

void f(std::vector<std::reference_wrapper<double>>) {}
void g() {
  std::vector<double> v(10);
  f({v[0], v[2], v[6]});
}

您說您不想創建一個新的向量並將所需的元素復制到其中-帶有指向3個元素的指針的新向量又如何呢? 還是帶有指向元素的指針的元組?

std::vector<Element> items { e0, e1, e2, e3, e4, e5, e6, e7 };
auto tuple = std::make_tuple(&items[0], &items[2], &items[6]);

還是僅帶有3個字段的自定義參數結構-指向3個矢量元素的指針?

還是帶有指向3個矢量元素的指針的原始數組? (也許帶有附加的數組大小函數參數)

std::vector<Element> items { e0, e1, e2, e3, e4, e5, e6, e7 };
Element subItems[3] { &items[0], &items[2], &items[6] };

可能有很多,但我會去尋找一個帶有副本的新向量,除非這樣做不必要地昂貴,在這種情況下,指向原始向量的指針將是第二選擇。 創建向量實際上不太可能是性能問題。

您可以將索引與向量一起傳遞:

std::vector<unsigned> indices = { 1, 3, 5 };


void f(const std::vector<int>& X, const std::vector<unsigned>& idx)
{
    // Do something
}

您可以插入轉發功能為您選擇索引:

template <size_t... Is, typename F, typename C>
auto fwd_indices(F func, C& cont)
-> decltype(func(cont[Is]...))
{
    return func(cont[Is]...);
}

這是一個零拷貝,零對象的解決方案。 您可以這樣使用該功能:

std::vector<int> v = { .. };
fwd_indices<0, 2, 6>(some_func, v); // calls some_func(v[0], v[2], v[6]);
                                    // which hopefully takes them by-ref

如果您只知道在運行時需要轉發哪些索引,這是一個難題。 但是,如果您在編譯時知道它們,對我來說這似乎很干凈。

您可以傳遞一個迭代器向量:

#include <vector>
#include <iostream>

using itr_type = std::vector<double>::const_iterator;

void doSomethingWithItrVec(std::vector<itr_type> itr_vec) {
  for (auto itr : itr_vec)
    std::cout << *itr << "\n";
}

int main() {
    std::vector<double> v = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0};
    auto begin = v.cbegin();
    doSomethingWithItrVec({begin, begin + 2, begin + 6});
}

暫無
暫無

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

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