c++ - 如何在已声明的 vector 中插入一组传递给函数的值

标签 c++

让我们考虑这个 C++ 代码:

std::vector<int> v;
void setTipp(int& n1, int& n2, int& n3, int& n4, int& n5, int& n6) {
    //insert all 6 elements inside vector 
    //but not like v.pushback(n1); etc
    //also not like v.resize(6); v[0]=n1; etc
}

有没有一种方法可以自动将所有 6 个元素插入 vector v 中,即使 vector v 已经被贴标。

我想在 v 中插入值,如 v{n1,n2....n6};或者喜欢

for (int i=0; i<=6;i++){
//v.pusback(n1);pushback(n2) etc.
//or v[i]=n1....n6;  
}

有没有办法在不在函数“setTipp”中创建新 vector 或数组的情况下做到这一点

不做这样的事情:

void setTipp(int& n1, int& n2, int& n3, int& n4, int& n5, int& n6) {
 std::vector<int> tmp{n1,n2,n3,n4,n5,n6};
 v=tmp;
}

最佳答案

你可以使用 initializer_list:

std::vector<int> v;
void setTipp(int n1, int n2, int n3, int n4, int n5, int n6) {
    for (int i : {n1, n2, n3, n4, n5, n6}) {
        v.push_back(i);
    }
}

但我可能会将签名更改为:

void setTipp(const std::array<int, 6>& a) {
    v.insert(v.end(), a.begin(), a.end());
}

所以改变调用来自:

setTipp(4, 8, 15, 16, 23, 42);

setTipp({{4, 8, 15, 16, 23, 42}});

关于c++ - 如何在已声明的 vector 中插入一组传递给函数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56836317/

相关文章:

c++ - 对临时的常量引用

c++ - 如何在 C++ 的同一行上两次 getline()?

c++ - boost 属性树 : how to store pointers in it?

c++ - SDL 按键

c++ - AWS 签名版本 4 发生了什么变化

c++ - const_cast 将右值转换为 const ref

c++ - C++中的结构和类有什么区别?

c++ - 是返回一个缓冲区更好,还是返回一个适当大小的字符串更好?

c++ - 我可以从 NTFS 分区在 Ubuntu 中运行 C++ 项目吗?

c++ - 自动阈值分割