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

C++数值vector线性搜索及不重复随机数生成问题求助

Fixing Duplicate Random Numbers & Linear Search in C++ Vectors

Hey there! Let's break down your two main needs: generating 9 unique random numbers (fixing that duplicate issue first) and understanding linear search for numeric vectors.

First: Fixing the Unique Random Number Generator

Your current code has a key flaw: when you regenerate a number for v[m], you only check if it matches v[j]—but it might still duplicate an earlier element (like v[0] or v[1]) that's not in the current j iteration. That's why you're still seeing duplicates.

Plus, you mentioned needing 9 unique numbers, so we'll adjust the loop counts from 4 to 9. Here are two solid solutions:

Every time you generate a new random number, search the entire existing vector to make sure it's not already present. This is straightforward and ties directly into the linear search topic you're curious about:

#include <iostream>
#include <vector>
#include <ctime>
using namespace std;

// Linear search helper function to check if a number exists in the vector
bool contains(const vector<int>& vec, int num) {
    for (int n : vec) {
        if (n == num) {
            return true;
        }
    }
    return false;
}

int main() {
    srand(time(0));
    vector<int> v;
    const int targetCount = 9;
    const int maxNum = 10; // We're using 0-9, which has 10 unique values—perfect for 9 unique nums

    while (v.size() < targetCount) {
        int newNum = rand() % maxNum;
        if (!contains(v, newNum)) { // Use our linear search to check uniqueness
            v.push_back(newNum);
        }
    }

    // Print the result
    cout << "9 unique random numbers: ";
    for (int num : v) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

Solution 2: Shuffle a Predefined Range (More Efficient)

If your random number range is small (like 0-9 here), it's more efficient to create a list of all possible values, shuffle it, then take the first 9 elements. No need to repeatedly check for duplicates:

#include <iostream>
#include <vector>
#include <ctime>
#include <algorithm> // For shuffle
using namespace std;

int main() {
    srand(time(0));
    vector<int> v;
    const int targetCount = 9;

    // Fill vector with 0-9
    for (int i = 0; i < 10; i++) {
        v.push_back(i);
    }

    // Shuffle the vector
    random_shuffle(v.begin(), v.end());

    // Keep only the first 9 elements
    v.resize(targetCount);

    // Print the result
    cout << "9 unique random numbers: ";
    for (int num : v) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

Second: Linear Search for Numeric Vectors

Linear search is the simplest way to find an element in a vector—it checks each element one by one until it finds a match. Here are three common ways to implement it in C++:

1. Custom Loop (Full Control)

This is the manual approach, like the contains function we used earlier. You iterate through each element and compare it to your target:

int linearSearch(const vector<int>& vec, int target) {
    for (int i = 0; i < vec.size(); i++) {
        if (vec[i] == target) {
            return i; // Return index of the found element
        }
    }
    return -1; // Return -1 if not found
}

2. Use std::find (Standard Library)

The C++ Standard Library has a built-in linear search function in <algorithm>. It returns an iterator to the found element, or vec.end() if not found:

#include <algorithm>

// Example usage
vector<int> nums = {3, 7, 1, 9, 4};
int target = 9;

auto it = find(nums.begin(), nums.end(), target);
if (it != nums.end()) {
    cout << "Found at index: " << it - nums.begin() << endl;
} else {
    cout << "Not found" << endl;
}

3. Use std::any_of (Check Existence Only)

If you only need to know if the element exists (not its index), std::any_of is a clean option:

#include <algorithm>

vector<int> nums = {3, 7, 1, 9, 4};
int target = 5;

bool exists = any_of(nums.begin(), nums.end(), [target](int num) {
    return num == target;
});

cout << (exists ? "Element exists" : "Element does not exist") << endl;

Both of the random number solutions above will give you 9 unique values, and the linear search examples cover the core ways to search numeric vectors in C++.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 02:23:34