在c ++中使用列表而不是数组

时间:2014-02-15 10:10:03

标签: c++ oop

我刚刚开始学习c ++而我没有理解这个列表。我有一些使用该数组的代码。

#include <iostream>
#include <string>

using namespace std;

class test {
public:
string a,b;
};

int main(){
test param [3]; 
param[0].a = "asdf";
param[0].b = "ghjk";
param[1].a = "qwer";
param[1].b = "tyui";
param[2].a = "zxcv";
param[2].b = "vbnm";
cout << "param\ta\tb\n";
for(int i = 0; i<3; i++){
cout << i << "\t" << param[i].a <<
"\t" << param[i].b << endl;
}
}

如何使用列表实现相同的代码?以下是我尝试这样做的方法:

#include <list>
...
list <test> param;
param.push_back();
param.back().a = "asdf";
param.back().b = "ghjk";
...

第二次尝试:

...
test o; 
o.a = "asdf"; o.b = "ghjk";
param.push_back(o);
...

如你所知,它们都不起作用......

4 个答案:

答案 0 :(得分:2)

您需要将test个对象推入列表中。例如:

param.push_back(test());
param.back().a = "asdf";
param.back().b = "ghjk";

param.push_back({"asdf", "ghjk"});
param.push_back({ "qwer", "tyui" });
param.push_back({ "zxcv", "vbnm" });

请注意,std::list是双向链接列表,不支持随机访问。因此,它不一定是阵列的良好替代品。您可能需要查看std::vector

答案 1 :(得分:2)

首先通过

创建一个类测试的对象

test temp

然后正确初始化temp

temp.a="alpha";
temp.b="beta";

现在按下列表中的temp

param.push_back(temp);

答案 2 :(得分:0)

test test1;
test test2;
test test3;

test1.a = "asdf";
test1.b = "ghjk";
test2.a = "qwer";
test2.b = "tyui";
test3.a = "zxcv";
test3.b = "vbnm";

param.push_back(test1);
param.push_back(test2);
param.push_back(test3);

答案 3 :(得分:0)

例如

#include <iostream>
#include <string>
#include <list>

class test 
{
public:
    std::string a, b;
};

int main()
{
    std::list<test> l;
    l.push_back( { "asdf", "ghjk" } );
    l.push_back( { "qwer", "tyui" } );
    l.push_back( { "zxcv", "vbnm" } );

    std::cout << "param\ta\tb\n";
    int i = 0;
    for ( const test &t : l )
    {
        std::cout << i++ << '\t' << t.a 
                         << '\t' << t.b << std::endl;
    }
}

或者

#include <iostream>
#include <string>
#include <list>

class test 
{
public:
    std::string a, b;
};

int main()
{
    std::list<test> l;

    l.push_back( test() );
    l.back() = { "asdf", "ghjk" };
    l.push_back( test() );
    l.back() =  { "qwer", "tyui" };
    l.push_back( test() );
    l.back() = { "zxcv", "vbnm" };

    std::cout << "param\ta\tb\n";
    int i = 0;
    for ( const test &t : l )
    {
        std::cout << i++ << '\t' << t.a 
                       << '\t' << t.b << std::endl;
    }
}

或者

#include <iostream>
#include <string>
#include <list>

class test 
{
public:
    std::string a, b;
};

int main()
{
    std::list<test> l;

    l.push_back( test() );
    l.back().a = "asdf"; l.back().b = "ghjk";
    l.push_back( test() );
    l.back().a = "qwer"; l.back().b = "tyui";
    l.push_back( test() );
    l.back().a = "zxcv"; l.back().b = "vbnm";

    std::cout << "param\ta\tb\n";
    int i = 0;
    for ( const test &t : l )
    {
        std::cout << i++ << '\t' << t.a 
                       << '\t' << t.b << std::endl;
    }
}