You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

遍历结构体中多vector遇下标错误,求正确迭代存储访问方法

Fixing Vector Index Errors in Your Struct Iteration

Let's break down what's going wrong here and fix it step by step—your vector index errors are tied to a few critical logic and safety issues in your code.

Key Problems in Your Current Code

  • Early Loop Exit: Your return P1; statement is inside the while (tmp != NULL) loop. This means the function will bail out on the first iteration, never fully traversing your linked list and leaving most of your logic unexecuted.
  • Unchecked Vector Access: You increment i and access P1.playerID1[i] without verifying that i stays within the vector's valid bounds. When i exceeds the last index of the vector, you'll hit an out-of-bounds error.
  • Memory Leak: The line player_attributes *tmp = new player_attributes; allocates memory, but you immediately overwrite tmp with head—this allocated memory is never freed, creating a leak.

Solution: Safe Vector Iteration & Code Fixes

Here's a revised version of your code that addresses these issues with safer vector handling:

struct data {
    vector<string> playerID1;
    vector<string> playerID2;
    vector<string> overall;
} P1;

struct data P(string b) {
    int i = 0;
    player_attributes *tmp = head; // Remove unnecessary `new` to fix memory leak

    // First, ensure all parallel vectors have matching lengths
    if (P1.playerID1.size() != P1.playerID2.size() || P1.playerID1.size() != P1.overall.size()) {
        // Handle mismatch error (e.g., log a message or return early)
        return P1;
    }

    while (tmp != NULL) {
        if (tmp->potential == b) {
            // Check if we're still within vector bounds before accessing
            if (i < P1.playerID1.size()) {
                tmp->Id1 = P1.playerID1[i];
                tmp->Id2 = P1.playerID2[i];
                tmp->overrall_rating = P1.overall[i];
                i++;
            } else {
                // Ran out of vector elements before finishing the list—handle this error
                break;
            }
        }
        tmp = tmp->next; // Don't forget to move to the next linked list node!
    }

    return P1; // Move return outside the loop to finish traversal first
}

Even Safer: Use Vector Iterators

If you want to eliminate manual index management entirely (and avoid index errors altogether), use vector iterators:

struct data P(string b) {
    auto it_id1 = P1.playerID1.begin();
    auto it_id2 = P1.playerID2.begin();
    auto it_overall = P1.overall.begin();

    player_attributes *tmp = head;

    // Verify vector length consistency first
    if (P1.playerID1.size() != P1.playerID2.size() || P1.playerID1.size() != P1.overall.size()) {
        return P1;
    }

    while (tmp != NULL && it_id1 != P1.playerID1.end()) {
        if (tmp->potential == b) {
            tmp->Id1 = *it_id1;
            tmp->Id2 = *it_id2;
            tmp->overrall_rating = *it_overall;

            // Advance all iterators together
            ++it_id1;
            ++it_id2;
            ++it_overall;
        }
        tmp = tmp->next;
    }

    return P1;
}

Key Takeaways

  • Always validate vector bounds before accessing elements via index, or use iterators to skip manual index tracking entirely.
  • Make sure your parallel vectors (playerID1, playerID2, overall) have identical lengths to avoid mismatched data assignments.
  • Double-check loop control logic—ensure you're advancing through your linked list and only returning after the loop completes.

内容的提问来源于stack exchange,提问作者Daniel Mangal

火山引擎 最新活动