使用boost assign初始化具有固定大小的向量向量

48

有一个固定大小的向量向量,

vector<vector<int> > v(10);

我希望将其初始化为具有所有元素的一维向量,其初始化值为1。

我已经使用了Boost Assign,如下所示:

v = repeat(10,list_of(list_of(1)));

而且我遇到了编译错误

error: no matching function for call to ‘repeat(boost::assign_detail::generic_list<int>)’

怎么做到呢?

4个回答

91

这个不使用 boost::assign,但能满足你的需求:

vector<vector<int>> v(10, vector<int>(10,1));

这将创建一个包含10个int向量的向量,每个向量都包含10个int


8
为什么会有“1”? - anilbey
4
问题询问如何将向量的所有成员初始化为1。向量构造函数的第二个参数是要复制的值。 - Weston

54

你不需要使用boost来实现所需的行为。以下代码创建一个vector,其中包含10vector<int>,每个vector<int>中包含10个值为1int

std::vector<std::vector<int>> v(10, std::vector<int>(10, 1));

5
这是发布的第一个答案,它是最好的答案,但却既不���被采纳的答案,也不是票数最高的答案。叹息,生活并不公平。 - abcd
1
我认为这是因为它有 >>,即没有空格的 > :p - krozaine
@dbliss 刚刚查看了编辑历史,看起来楼主在上传完答案后就将其删除了。也许他在完成答案后看到了其他人的答案,不想发表与其他人相同的内容(尽管他是第一个)。无论如何,这对他来说感觉很糟糕。 - deadLock

6

我会尝试为那些刚接触C++的人解释一下。向量 mat 的优点是,您可以使用 [] 运算符直接访问其元素,几乎没有任何代价。

int n(5), m(8);
vector<vector<int> > mat(n, vector<int>(m));

mat[0][0] =4; //direct assignment OR

for (int i=0;i<n;++i)
    for(int j=0;j<m;++j){
        mat[i][j] = rand() % 10;
    }

当然,这不是唯一的方法。如果您不添加或删除元素,则还可以使用本地容器mat [],它们只是指针。这是我最喜欢的方式,使用C ++:

int n(5), m(8);
int *matrix[n];
for(int i=0;i<n;++i){
    matrix[i] = new int[m]; //allocating m elements of memory 
    for(int j=0;j<m;++j) matrix[i][j]= rand()%10;
}

这样,您就不必使用#include <vector>了。希望这样更清晰易懂!

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


int main(){
    int n; cin >> n;
    vector<vector<int>> v(n);
    //populate
    for(int i=0; i<n; i++){
        for(int j=0; j<n; j++){
            int number; cin >> number;
            v[i].push_back(number);
        }
    }
    // display
    for(int i=0; i<n; i++){
        for(int j=0; j<n; j++){
            cout << v[i][j] << " ";
        }
        cout << endl;
    }
}

输入:

4
11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44

输出:

11 12 13 14
21 22 23 24
31 32 33 34
41 42 43 44

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接