簡體   English   中英

與向量的每個第 2、第 3 和第 4 個元素交互,直到 vecotr 結束

[英]Interact with every 2nd, 3rd, and 4th element of a vector until end of vecotr

假設我有一個字符串向量,每個字符串都包含一個 4 字母的字符串。 向量中字符串的確切數量可能會根據輸入而變化,但所有字符串的字符總數總和將始終為 16 的倍數(例如 64 和 784)。 假設對於 n 個向量,我想訪問向量的每個第 2、第 3 和第 4 個元素,跳過向量中的第 1、第 5、第 9、第 13 等元素。 編寫允許我使用 C++ 交互和編輯向量中的這些字符串的循環或 function 的最佳方法是什么?

這個?

     for(int i = 0; i< svec.size(); i++){
        if(i%4!=0){
            // process string here
            noodleOn(svec[i]);
        }
     }

假設你的意思是“第一個”-“索引為 0 的那個”等。

您可以制作一個循環,每次迭代將索引增加 4。 如何設置初始索引值取決於當被問及“如果向量恰好包含許多不能被 4 整除的字符串怎么辦”時,您發現最容易推理的內容?

我發現這很容易推理:

  • 從您要選擇的前 4 個索引中的最高索引開始。 那是3
  • 使用帶有該索引的下標運算符並減去210來選擇第二個、第三個和第四個元素。
  • 最后將索引步進 4。

對我來說,這清楚地表明它永遠不會越界訪問向量:

#include <iostream>
#include <string>
#include <vector>

void interact(const std::string& x2, const std::string& x3, const std::string& x4) {
    std::cout << x2 << ',' << x3 << ',' << x4 << '\n';
}

int main() {
    std::vector<std::string> vs{"Hello", "world", "This", "is",
                                "fun",   "don't", "you",  "think"};

    for (size_t idx = 3; idx < vs.size(); idx += 4) {
        interact(vs[idx - 2], vs[idx - 1], vs[idx - 0]);
        //            2nd          3rd          4th
    }
}

Output:

world,This,is
don't,you,think

暫無
暫無

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

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