Ata
Ata

Reputation: 12554

Does C++ have anything like List<string> in C#?

Does C++ has anything like List<> in C#? Something like List<string> for storing an array of strings.

Upvotes: 12

Views: 18498

Answers (3)

Sven
Sven

Reputation: 22693

The answer is actually

std::vector<std::string>

std::list is a linked list, not an array like C#'s List<T> class.

E.g.

#include <iostream> // iostream is for cout and endl; not necessary just to use vector or string
#include <vector>
#include <string>
using namespace std;

int main()
{
    vector<string> list;
    list.push_back("foo");
    list.push_back("bar");
    for( vector<string>::const_iterator it = list.begin(); it != list.end(); ++it )
        cout << *it << endl;

    return 0;
}

The std::list class is actually equivalent to C#'s LinkedList<T> class.

Upvotes: 22

elder_george
elder_george

Reputation: 7879

C++ has std::vector template class that corresponds to C#'s List. It also has std::list template that corresponds to C# SingleLinkedList.

One must be prepared that in C++ vector and list call copy constructor of item. So, for each string you have a copy will be created.

So, if you are limited on memory or if you want to store the same strings in multiple collections, you'd better use std::vector<std::string*> or std::vector<char*> instead of std::vector<string>.

Upvotes: 0

Alois Kraus
Alois Kraus

Reputation: 13545

A List in .NET is not a linked list. The data structure you are looking for is a resizeable array.

std::vector<std::string> list;

Upvotes: 7

Related Questions