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

使用STL实现std::vector按指定索引元素置换的最简方案

实现按索引置换std::vector的permute函数

嘿,刚好碰到过类似的需求,我来给你分享一下怎么实现这个按索引置换向量的函数~

咱们的需求很明确:给定一个std::vector<T>类型的原向量,以及一个存储索引的std::vector<int>,要返回一个按这些索引规则置换后的新向量。

完整实现代码

直接上可运行的模板函数,还加了合法性检查避免踩坑:

#include <vector>
#include <stdexcept> // 用于抛出异常

template<typename T>
std::vector<T> permute(const std::vector<T>& vec, const std::vector<int>& indices) {
    // 第一步:检查索引集合和原向量的大小是否匹配
    if (indices.size() != vec.size()) {
        throw std::invalid_argument("Indices size must match the original vector's size");
    }

    std::vector<T> result(vec.size());
    for (size_t i = 0; i < indices.size(); ++i) {
        // 额外检查单个索引是否在合法范围内
        const int idx = indices[i];
        if (idx < 0 || static_cast<size_t>(idx) >= vec.size()) {
            throw std::out_of_range("Index out of bounds");
        }
        // 按索引规则赋值:结果的第i个元素 = 原向量的indices[i]位置元素
        result[i] = vec[idx];
    }
    return result;
}

代码说明

  • 合法性检查:这一步很重要!如果索引数组和原向量大小不一致,置换逻辑根本不成立,直接抛异常提醒调用者;另外也检查了单个索引是否越界,避免访问非法内存。
  • 高效初始化:直接创建和原向量同大小的结果向量,避免后续扩容带来的性能损耗。
  • 核心逻辑:遍历每个索引,把原向量对应位置的元素放到结果向量的对应位置,完成置换。

示例用法

给你写个简单的测试例子,一看就懂:

#include <iostream>
#include <string>

int main() {
    std::vector<std::string> original = {"apple", "banana", "cherry", "date"};
    std::vector<int> indices = {2, 0, 3, 1}; // 想要的置换规则

    try {
        auto permuted_vec = permute(original, indices);
        for (const auto& item : permuted_vec) {
            std::cout << item << " ";
        }
        // 输出:cherry apple date banana
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
    return 0;
}

额外说明

如果你的索引规则是反向置换(比如indices[i]表示原向量第i个元素要放到结果的哪个位置),那只需要把核心逻辑改成:

result[indices[i]] = vec[i];

不过这种情况要注意索引不能重复,否则会出现元素被覆盖的问题哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:35:34