簡體   English   中英

如何在帶有 X 個元素的 std::vector 中從 p 中提取 n 個元素

[英]How can i extract n elements out of p in a std::vector with X elements

我有一個包含 X 元素的向量,如何從向量中從 p(示例中為 6)中提取 n 個元素(下例中為 3)? 這是我的做法。

//vector<int> a;
std::vector<int> a {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
                       23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35};

int X = a.size();

// code to extract 3 elements of 6 until the end of the vector
for (int i=0; i< a.size(); i+=6)
{

        if (i >= a.size())
        {
            break;
        }
        else
        {
            sub_indices.push_back(i);
        }

        if ( (i+1) >= a.size())
        {
            break;
        }
        else
        {
            sub_indices.push_back(i+1);
        }

        if ((i+2) >= a.size())
        {
            break;
        }
        else {
            sub_indices.push_back(i+2);
        }
}

顯示結果為 output:

10 11 12 (drop three elements) 16 17 18 (drop three elements) 22 23 24  (drop three elements) 28 29 30 (drop three elements) 34 35

我是這樣做的,但誰能告訴我一個更有效的方法?

這是解決方案:

#include <vector>
#include <iostream>

int main () {

  // Better to initilize the vector like this instead of using multiple push_back
  std::vector<int> a;
  for (int i=10; i<36; ++i)
    a.push_back (i);

  // Here is another method to initilize your vector:
//   std::vector<int> a {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
//                       23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35};

  // Here you loop over all elements and only select the three first elements
  // of every six elements:
  for (int i=0; i<a.size(); ++i) 
    if (i%6 < 3)
      std::cout << a[i] << std::endl;

  return 0;
}

% 運算符給出兩個 int 值相除的余數。

重新組織你的向量,使每個元素都是 3 int s

vector< std::tuple<int, int, int> > a = {10,11,12,13, ... };

然后使用所有其他元素,例如:

for (size_t i{}; i<a.size(); ++i) {
  if (i%2 != 0) {
   std::cout << a[i] << std::endl;
  }
}

暫無
暫無

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

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