It is not clear whether there is a value of 3 functions, and whether there is an index in a QList<int>

  QList<int> ppc; ppc[0]=100; ppc[1]=200; ppc[2]=300; ppc[3]=400; int res = ppc.at(4); 

Of course, an error window pops up, but how to find out if the key is in the list is not clear, there must be a function there.

    1 answer 1

    The key concept refers to dictionaries (dict, map), and for lists, arrays and sets (list, array, set), access to the elements is done through an index that starts from 0 Π΄ΠΎ <Ρ€Π°Π·ΠΌΠ΅Ρ€ - 1> or from 1 Π΄ΠΎ Ρ€Π°Π·ΠΌΠ΅Ρ€ .

    Therefore, to check the availability of the index, you need to refer to the size and compare the size with the index.

    QList has 3 identical functions for checking the size: count, size and length.

    For your example, add a verification:

     int index = 4; // Для индСксации ΠΎΡ‚ 0 Π΄ΠΎ n - 1 // А для индСксации ΠΎΡ‚ 0 Π΄ΠΎ n, ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠ° измСнится Π½Π°: index <= ppc.size() if (index < ppc.size()) { int res = ppc.at(index); // ΠΈΠ»ΠΈ ppc[index] } 

    QList with an incorrect index does not throw an exception (as historically in Qt), but, for example, in java there is an ArrayIndexOutOfBoundsException , and in python it is an IndexError .

    Then, instead of checking, you can catch an exception, for example, then the code with checking would change to something like this:

     int index = 4; try { int res = ppc.at(index); } catch (IndexError) { // ignore } 
    • THX. I also thought about it. Although it is strange why not to make such a function, in my opinion it is much more logical than to do 3 identical functions. - Madoka Magica
    • one
      @MadokaMagica, firstly, in c ++, uncaught exceptions in constructors can lead to memory leaks, and in destructors to calling std::termiante . Secondly, checking the boundaries of the range give additional costs that are not always necessary, so it was wiser to leave them on the conscience of the library user. - yrHeTaTeJlb