错误:标量对象'v'需要初始值设定项中的一个元素
error: scalar object 'v' requires one element in initializer
嗨,
我有一些简单的代码如下所示,保存到一个文件中(比如stock_portfolio.cxx)
我正试图将其编译为:g++ stock_portfolio.cxx
error: scalar object 'v' requires one element in initializer
我的gcc版本是:gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-52)
#include<iostream>
#include<vector>
int main() {
std::vector<int>v = {1,2,3,4,5,6};
//std::vector<string> four_star_stocks;
for(int i = 0; i < v.size(); ++i){
std::cout << "Stock S&P: " << v[i] << "n";
}
std::cout << "========================" << "n";
std::cout << "Totals : " << v.size() << "n";
return 0;
}
列表初始化仅在C++的C++11中引入。gcc 4.1版不支持C++11(请参阅https://gcc.gnu.org/projects/cxx0x.html)
我不清楚你的问题是询问建议的解决方案/修复方案,还是解释为什么你的代码不会编译。
在循环中初始化向量,如下所示:
for(int i = 1; i <= 6; ++i)
v.push_back(i);
正如cdhowie所建议的,您的gcc版本不支持初始值设定项列表(您至少需要g++版本4.4,源代码)。如果您得到一个新的(添加标志-std=c++0x
或-std=gnu++0x
),那么您可以看到以下内容:
std::vector<int> v = {1,2,3,4,5,6};
或
如果你想用初始化器列表来实现这一点,那么你应该使用std::initializer_list,如下所示:
#include <iostream>
#include <vector>
#include <initializer_list>
template <class T>
struct S {
std::vector<T> v;
S(std::initializer_list<T> l) : v(l) {
std::cout << "constructed with a " << l.size() << "-element listn";
}
void append(std::initializer_list<T> l) {
v.insert(v.end(), l.begin(), l.end());
}
std::pair<const T*, std::size_t> c_arr() const {
return {&v[0], v.size()}; // list-initialization in return statement
// this is NOT a use of std::initializer_list
}
};
template <typename T>
void templated_fn(T) {}
int main()
{
S<int> s = {1, 2, 3, 4, 5}; // direct list-initialization
s.append({6, 7, 8}); // list-initialization in function call
std::cout << "The vector size is now " << s.c_arr().second << " ints:n";
for (auto n : s.v) std::cout << ' ' << n;
std::cout << 'n';
std::cout << "range-for over brace-init-list: n";
for (int x : {-1, -2, -3}) // the rule for auto makes this ranged for work
std::cout << x << ' ';
std::cout << 'n';
auto al = {10, 11, 12}; // special rule for auto
std::cout << "The list bound to auto has size() = " << al.size() << 'n';
// templated_fn({1, 2, 3}); // compiler error! "{1, 2, 3}" is not an expression,
// it has no type, and so T cannot be deduced
templated_fn<std::initializer_list<int>>({1, 2, 3}); // OK
templated_fn<std::vector<int>>({1, 2, 3}); // also OK
}
源
相关文章:
- lower_bound()返回最后一个元素
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 检查 2D 网格的某个元素是否与另一个元素共享对角线、水平线或垂直线
- 仅显示链表的最后一个元素
- push_back通过自行创建的对象获取最后一个元素的向量
- 使用 map.end() 访问 map 的最后一个元素
- 如何知道地图中的最后一个元素是否被删除?
- 选择一个元素而不是一个对象的数组的原因
- std::矢量保存 只推送最后一个元素
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 反转后不返回最后一个元素
- 如何在新数组较小时创建新数组并将旧数组的最后一个元素复制到新数组中?
- 访问 for_each 函数中的前一个元素
- 在 QListView 中显示最后一个元素
- 从 std::vector 中选择一个元素,而不是给定元素
- C++:在进行切片时对迭代器的约定,特别是对于访问最后一个元素并最终将其删除
- 遍历列表包含排除最后一个元素的内容
- 如何从一个无序集合中获取一个元素