簡體   English   中英

什么是“bool a_indexable = i < static_cast<int> (a.size())”在下面的代碼中是什么意思?</int>

[英]What does "bool a_indexable = i < static_cast<int>(a.size())" mean in the following code?

以下是代碼:

#include <vector>
#include <string>

std::vector<std::string> zip(
    const std::vector<std::string> & a, 
    const std::vector<std::string> & b) {
  std::vector<std::string> result;
  for (int i = 0; ; ++i) {
    bool a_indexable = i < static_cast<int>(a.size()); //I couldn't get what the following two lines mean as I asked in the title, I couldn't get what bool means here and I couldn't get what i < static_cast<int>(a.size()) means here
    bool b_indexable = i < static_cast<int>(b.size());
    if (!a_indexable && !b_indexable) {
      break;
    }
    std::string element;
    if (a_indexable) {
      element += a[i];
    }
    if (b_indexable) {
      element += b[i];
    }
    result.push_back(element);
  }
  return result;
}

我知道static_cast<int>在代碼中的含義,但我對它的組合感到困惑,尤其是像i < static_cast<int>(b.size()) 如果你能幫助我,請解釋一下。

a_indexable是一個 boolean,指示i是否是向量a的有效索引。

計算a_indexable的一種簡單方法是:

bool a_indexable = i < a.size();

然而a.size()std::size_t類型,它是一個無符號 integer。混合有符號整數和無符號整數很麻煩,因此大多數編譯器會發出警告i < a.size() 解決方案是將a.size()顯式轉換為i在您的示例中喜歡的類型:

bool a_indexable = i < static_cast<int>(a.size());

a.size()b.size()這里指的是std::vector::size() std::vector::size()返回一個size_t (通常是一個unsigned int ),而不是一個int

正如您在這個問題中看到的,將intsize_t進行比較會發出警告。 通過將static_cast轉換為 int,編寫此代碼的人將擺脫編譯器的警告。

它實際上是一種確定給定索引是否對向量有效並因此確保您不會嘗試讀取超出向量末尾的方法。 如果索引小於大小,則它是有效的。 轉換避免了在比較中混合有符號和無符號值的警告。

但是,我可能只是將i設為size_t類型,這樣就沒有必要進行這種轉換了,尤其是因為i在 scope 中非常有限。


事實上,我會以不同的方式編寫它,以便完全避免這種邏輯,通過預先獲取公共長度(兩個長度的最小值)然后分段處理它,比如(使用某種類型別名來制作代碼有點可讀性,並且作為一個完整的程序顯示了最小的測試工具):

#include <vector>
#include <string>

using vecString = std::vector<std::string>;
vecString zip(const vecString &a, const vecString &b) {
    vecString result;

    auto asz = a.size();
    auto bsz = b.size();
    auto common_sz = std::min(asz, bsz);

    // Handle common size, both vectors are guaranteed
    // to have elements at these indices.

    for (size_t i = 0; i < common_sz; ++i)
        result.push_back(a[i] + b[i]);

    // Handle where sizes differ, only ONE of these loop
    // bodies will be executed, depending on which is
    // larger. Of course, if sizes were identical,
    // neither loop body will execute.

    for (size_t i = common_sz; i < asz; ++i)
        result.push_back(a[i]);

    for (size_t i = common_sz; i < bsz; ++i)
        result.push_back(b[i]);

    return result;
}

#include <iostream>

int main() {
    std::vector<std::string> vec1, vec2;

    vec1.push_back("pax");
    vec1.push_back("is");
    vec1.push_back("clever");

    vec2.push_back("diablo");

    auto zipVec = zip(vec1, vec2);
    for (const auto &zipString: zipVec)
        std::cout << zipString << '\n';
}

暫無
暫無

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

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