You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用for循环筛选vector元素?非永久删除的多组返回实现

Solution: Generate Element Pairs Without Modifying the Original Vector

Hey there! I totally get why those permanent deletion solutions weren't working for you—you just need to grab those element pairs without touching the original vector at all. Let's fix this with a straightforward approach that uses indices instead of modifying your data.

The Core Idea

Since you need exactly three pairs: (y,z), (x,z), (x,y), this boils down to excluding one element at a time from your 3-element vector and pairing the remaining two. No deletions required—we'll just reference elements by their positions.

Code Example (C++)

Here's a reusable function that generates the pairs you need, leaving your original vector completely intact:

#include <vector>
#include <utility>
#include <iostream>

template<typename T>
std::vector<std::pair<T, T>> getTargetCombinations(const std::vector<T>& input_vec) {
    std::vector<std::pair<T, T>> result;
    
    // Quick validation: make sure we have exactly 3 elements
    if (input_vec.size() != 3) {
        return result;
    }

    // Loop through each index we want to exclude (0, 1, 2)
    for (size_t exclude_idx = 0; exclude_idx < input_vec.size(); ++exclude_idx) {
        std::pair<T, T> current_pair;
        
        // Pick the two elements that aren't the excluded one
        if (exclude_idx == 0) {
            // Exclude first element (x), take y and z
            current_pair = {input_vec[1], input_vec[2]};
        } else if (exclude_idx == 1) {
            // Exclude second element (y), take x and z
            current_pair = {input_vec[0], input_vec[2]};
        } else {
            // Exclude third element (z), take x and y
            current_pair = {input_vec[0], input_vec[1]};
        }
        
        result.push_back(current_pair);
    }

    return result;
}

// Test it out!
int main() {
    std::vector<int> my_vec = {10, 20, 30}; // x=10, y=20, z=30
    auto combinations = getTargetCombinations(my_vec);

    // Print the results
    for (const auto& pair : combinations) {
        std::cout << "(" << pair.first << ", " << pair.second << ")\n";
    }

    // Output will be:
    // (20, 30) → (y,z)
    // (10, 30) → (x,z)
    // (10, 20) → (x,y)
    return 0;
}

Why This Works

  • No modifications to the original vector: We're only reading elements via their indices, not adding/removing anything.
  • Flexible: The template works with any vector type (int, string, custom objects—you name it).
  • Clear and maintainable: The loop explicitly handles each exclusion case, making it easy to adjust if your requirements change later.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:18:43