c++ - 将数据从 vector 推回到 map 的 vector

标签 c++

我创建了一个名为 select_p 的 map ,该 map 的 vector 称为 pts。我已经将数据存储在一个数组中,我想将这些数据推送到我的 map vector 中。我通过将数组的值插入新 vector 然后推回我的 map 来尝试这个。但是它不起作用请帮我更正这些代码?谢谢

#include<iostream>
#include<cstdlib>
#include <map>
#include <vector>

using namespace std;
int main()
{
    int M=7;
    int N=6;
    int i=0;
    int * temp;
    map<int,vector<int> > select_p;
    vector<int>pts;

    for (int m=0; m<M; m++)
    {
        for (int n=0; n<N; n++)
        {
            vector<int>id;
            if (n==0 && m==5)
            {
               temp = new int[3,i+N,i+N+1,i+1];
               unsigned ArraySize = sizeof(temp) / sizeof(int);
               id.insert(id.begin(),temp[0], temp[ArraySize]);
               select_p[i].push_back(id);
            }
            i++;
        } 
    }
    delete[] temp;

    system("PAUSE");   
    return 0;   
}

最佳答案

for (int m=0; m<M; m++) {
    for (int n=0; n<N; n++) {
        if (n==0 && m==5) {

当您实际上只对一对 m 值执行任何操作时,为什么要循环?和 n ?循环在这里完全没用;只需设置 n = 0 即可获得相同的效果和 m = 5 .

temp = new int[3,i+N,i+N+1,i+1];

无论您认为它做什么,它都不是。这相当于 temp = new int[i+1]; . [] 中的其余表达式没有影响。

也就是说,你不应该使用 new在您的程序中创建数组。使用 std::vector ;正确使用它要容易得多。

unsigned ArraySize = sizeof(temp) / sizeof(int);

这是行不通的。当您动态分配一个数组时,您有责任跟踪其中有多少元素。给定一个指向动态分配数组的指针(如此处的 temp),无法确定数组中元素的数量。

你所拥有的相当于sizeof(int*) / sizeof(int) ,这不会达到您的预期。

id.insert(id.begin(),temp[0], temp[ArraySize]);

std::vector::insert采用一系列迭代器:您为其提供了两个值。大概你想使用 temp ,指向动态分配数组的初始元素,temp + i + 1 , 它指向数组末尾的一个。也就是说,由于您没有设置数组中元素的值,您正在复制未初始化的内存,这可能不是您想要做的。

select_p[i].push_back(id);

select_p[i]std::vector<int> . std::vector<int>::push_back()需要一个int附加到序列中。大概你只是想使用分配来分配 idselect_p[i] .

你应该得到 a good introductory C++ book如果你想学习用 C++ 编程。很抱歉,您的程序毫无意义。

关于c++ - 将数据从 vector 推回到 map 的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5643476/

相关文章:

c++ - 高效安全地分配唯一 ID

c++ - SDL 2.0 中不显示图像

C++20 - 模板参数推导/替换问题

c++ - printf %g 和 %f 之间的零填充差异

c++ - 在C++中传递链接列表而不会导致内存泄漏

c++ - std::reduce 与仿函数

c++ - 在 ANSI C 中定义的结构的 STL 映射

c++ - 通过 SOCKS5 c++ 发送和接收

c++ - 快速排序不排序 C++

c++ - 在 Qt 中为形状设置适当的颜色