如何用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
相关产品推荐
相关产品推荐

