我的印象是可以使用变量整数创建向量。我从第二个答案得到了这个印象:How to create an array when the size is a variable not a constant?
但是我仍然会收到以下代码的“constant int”错误消息:
#include <vector>
size_t ports_specified = std::count(Ports.begin(), Ports.end(), '+');
const int num_ports = static_cast<int>(ports_specified++);
std::vector<string> port_info[num_ports];
答案 0 :(得分:3)
详情很重要。
std::vector<string> port_info[num_ports];
这是声明num_ports
个std::vector<string>
个元素的静态数组。静态数组需要编译时常量,而不是运行时常量,因此需要错误。
std::vector<string> port_info(num_ports);
这是声明使用std::vector<string>
作为输入值构建的单个num_ports
。
换句话说,使用括号而不是括号。
答案 1 :(得分:2)
您正在尝试创建一个n vector<string>
的数组;
不是n个元素的vector<string>
。
要在 C ++ 11 中执行后者,vector支持一个带size_type
的构造函数。
explicit vector( size_type count );
在 C ++ 14 中,它已更改为默认的分配器。
explicit vector( size_type count, const Allocator& alloc = Allocator() );
你可以像这样构造一个10个整数的向量:
#include <iostream>
#include <vector>
int main(){
std::vector<int> v(10);
std::cout << v.size() << '\n';
for (auto it: v){
std::cout << it << " "; //prints: 0 0 0 0 0 0 0 0 0 0
}
}
向量使用default initialization,因此保证整数值为零。
您还可以设置初始值:
#include <iostream>
#include <vector>
int main(){
std::vector<int> v(10,7);
std::cout << v.size() << '\n';
for (auto it: v){
std::cout << it << " "; //prints: 7 7 7 7 7 7 7 7 7 7
}
}