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

使用make_pair赋值pair数组触发CLion警告,求替代赋值方法

Fixing the pair::operator=(type)' is deleted Warning in CLion

Hey there, let's work through this issue you're hitting. First off, it's odd that CLion flags that assignment as invalid even though your program runs—this is likely a false positive from the IDE's static analysis, but it's still worth cleaning up the code to avoid the warning and make it more idiomatic.

Here are a few solid alternatives to initialize your pair<string, int> array:

1. Aggregate Initialization (C++11+)

The cleanest approach is to initialize the array directly when you declare it. Thanks to C++11's aggregate initialization rules, you can set all elements to your desired default values in one line:

// All elements auto-initialize to (empty string, 0)
pair<string, int> mostOftenPairs[10] = {};

If you prefer being explicit (though it's not required here), you can also write out the initial values:

pair<string, int> mostOftenPairs[10] = {{"", 0}, {"", 0}, {"", 0}, {"", 0}, {"", 0}, 
                                        {"", 0}, {"", 0}, {"", 0}, {"", 0}, {"", 0}};

The first version works because any uninitialized elements in the array will be value-initialized, which gives you an empty string and 0 for the int automatically.

2. Use std::fill for Post-Declaration Initialization

If you need to reinitialize the array later (not just when you declare it), std::fill is a more idiomatic replacement for a manual loop:

#include <algorithm> // Required for std::fill
#include <iterator>  // Required for std::begin/std::end

// ...

std::fill(std::begin(mostOftenPairs), std::end(mostOftenPairs), 
          std::pair<std::string, int>());

This will set every element in the array to a default-constructed pair<string, int> (empty string + 0) without triggering the IDE warning.

3. In-Place Construction (For Container Alternatives)

While you're using a raw array here, if you ever switch to a container like std::array or std::vector, you can construct elements in place to avoid assignment entirely:

#include <array>

std::array<std::pair<std::string, int>, 10> mostOftenPairs;
for (auto& pair : mostOftenPairs) {
    // Construct the pair directly in its memory slot
    pair.emplace("", 0);
}

The core quirk with your original code is that CLion's analyzer might be incorrectly flagging the assignment of a temporary pair (from make_pair) to the array elements. Using the methods above will resolve the warning and make your code more readable and aligned with modern C++ practices.

内容的提问来源于stack exchange,提问作者patryk-szwed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:13:21