0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

warning: range-based for loop is a C++11 extension [-Wc++11-extensions]のエラーに対して

Posted at

背景

競プロに挑んでいる最中に題意のようなエラーに直面した。

for.cpp
#include <iostream>
#include <vector>

int main(){
    int N;
    std::cin >> N;

    std::vector<int> numbers;
    for (int i = 0; i < N; ++i){
        int num;
        std::cin >> num;
        numbers.push_back(num);
    }

    for (int num : numbers){
        std::cout << num << " ";
    }

    return 0;
}

解決策

  • C++11以降のバージョンのコンパイラを使用する
  • 警告を無視する
  • 通常のforループを使用する

C++11以降のバージョンのコンパイラを使用する

C++11の機能がサポートされているコンパイラを使用することで、警告を回避することができます。

警告を無視する

コードの最初に以下のような行を追加して、警告を無視するように指示することができます。ただし、この方法は推奨されるものではありません。

#pragma GCC diagnostic ignored "-Wc++11-extensions"

通常のforループを使用する

範囲ベースのforループの代わりに通常のforループを使用することで、警告を回避することができます。

以下は、通常のforループを使用した範囲ベースのforループの代替例です。

#include <iostream>
#include <vector>

int main() {
    std::vector<int> myVector = {1, 2, 3, 4, 5};

    std::cout << "ベクターの要素: ";
    for (size_t i = 0; i < myVector.size(); ++i) {
        int num = myVector[i];
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?