i'm tying to check if a specific vector element is initialized... i googled it and i found vector::empty but it seems it doesn't work for me because it keeps returning true at any circumstances!!!

int main() {
int n, k;
cin >> n >> k;
auto tasks = new vector<list<int> *>(n);
tasks->insert(tasks->begin(), new list<int>);
tasks->insert(tasks->begin() + 1, new list<int>);
tasks->insert(tasks->begin() + 2, new list<int>);
tasks->insert(tasks->begin() + 3, new list<int>);
tasks->insert(tasks->begin() + 4, new list<int>);
if (tasks->at(2)->empty()) cout << "empty";
return 0;}


  • nquas
    nquas 回复

    Because you are not calling std::vector::empty(), you call std::list::empty().

    You insert 5 empty lists at the beginning of a vector, and then you call empty() on list at index 2.

    Side note: Your vector is created with n lists and then you insert 5 more. Are you sure this is intended behaviour?

    Side note 2: you are using far too much new. Make your life easier and stop it:

    auto tasks = vector<list<int>>(n);
    tasks.insert(tasks.begin(), list<int>{});
    tasks.insert(tasks.begin() + 1, list<int>{});
    tasks.insert(tasks.begin() + 2, list<int>{});
    tasks.insert(tasks.begin() + 3, list<int>{});
    tasks.insert(tasks.begin() + 4, list<int>{});
    if ( cout << "empty";
  • noptio
    noptio 回复

    You are calling empty() on the third element of the vector, which is of type std::list and also has an empty() member function.