错误:标量对象' v'在初始化程序中需要一个元素

时间:2014-10-09 21:28:44

标签: c++ vector

您好,

我有一些简单的代码如下所示,保存到文件中(让我们说一下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;
}

2 个答案:

答案 0 :(得分:2)

list-initialization仅在C ++ 11中引入了C ++。 gcc 4.1版不支持C ++ 11(参见https://gcc.gnu.org/projects/cxx0x.html

我不清楚,如果您有问题是要求建议的解决方案/修复或解释为什么您的代码无法编译。

答案 1 :(得分:0)

在循环中初始化矢量,如下所示:

for(int i = 1; i <= 6; ++i)
  v.push_back(i);

正如cdhowie建议的那样,你的gcc版本不支持初始化列表(你至少需要g ++ 4.4版,source)。如果你得到一个更新的(添加标志-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 list\n";
    }
    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
}

Source