代码之家  ›  专栏  ›  技术社区  ›  Karnivaurus

将一个向量附加到另一个向量

c++
  •  -1
  • Karnivaurus  · 技术社区  · 8 年前

    我想动态地将一个向量附加到另一个向量上,这样我就可以建立一个矩阵, x .

    int main()
    {
        vector< vector<float> > x;
        vector<float> y = {1, 2, 3};
        x.insert(x.end(), y.begin(), y.end()) ;
    
        return 0;
    }
    

    但这给了我一个错误:

    /usr/include/c++/5/bits/stl_algobase.h:340: error: no match for 'operator=' (operand types are 'std::vector<float>' and 'float')
            *__result = *__first;
                      ^
    

    有什么想法吗?

    4 回复  |  直到 8 年前
        1
  •  4
  •   R Sahu    8 年前

    有什么想法吗?

    您正在尝试添加 float s到a vector<vector<float>> . 这就是问题所在。

    如果你改变 x

    vector<float> x;
    

    另一条线可以。

    如果你继续 x个 按原样,您可以添加 y 作为 x个 使用:

    x.push_back(y);
    
        2
  •  1
  •   Cameron Hall    8 年前
    vector<vector<float>> x;
    vector<float> y = {1, 2, 3};
    x.push_back(y);
    

    x.insert(x.end(), y.begin(), y.end()); 尝试插入 float s转换为a vector<vector<float>> .

        3
  •  1
  •   SoronelHaetir    8 年前

    您可以简单地执行以下操作:

    x.push_back(y);
    
        4
  •  0
  •   Stephan Lechner    8 年前

    具有 x.insert(x.end(), y.begin(), y.end()) ,您正在插入 float 值,其中 vector<float> -应为对象。

    如果要使用行的特定值初始化2D向量,只需使用不同的构造函数即可:

    int main()
    {
        vector<float> y = {1, 2, 3};  // row template object
        vector<vector<float>> x(10,y); // 2d vector with ten rows, each being a copy of row template y
    
        for (auto r : x) {
            for (auto c : r) {
                cout << c << " ";
            }
            cout << endl;
        }
    
        return 0;
    }